Wednesday, March 25, 2015

Wordpress: Pagination with WP_Query

Note: This is not for beginners, you need some knowledge of wordpress development


Code:This code covers: customs loop, propaly add pagination, properly trim the wp_content


<!-- add this line for pagination and in wp_query -->
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>

<!-- now add the $paged to wp_query -->
<?php $wp_query = new WP_Query(array('posts_per_page' =>6,'paged'=>$paged)); ?>


<!-- custom standard loop -->
<?php if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="header">
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h2>
</header>
<section class="entry-content">
<?php if (has_post_thumbnail()) { the_post_thumbnail();} ?>
<p>

<!--wp_trim_words, this function trim the content. in this case limit for 60 words -->
<?php echo wp_trim_words(get_the_content(), 60); ?>

<!--add read more link -->
<a href="<?php the_permalink() ?>">Read More &raquo;</a> </p>
</section>
</article>
<?php endwhile; ?>


<!-- pagination, (this works because in the above loop we passed 'paged' -->
<div class="nav-next alignleft"><?php previous_posts_link( '&laquo; Newer Posts' ); ?></div> <div class="nav-previous alignright"><?php next_posts_link( 'Older Posts &raquo;' ); ?></div>
<?php endif; ?>

No comments:

Post a Comment