Adding Paging to a Loop in WordPress
If you have requirements of pagination in your blog, then you will need to take a few extra steps for the pagination. The global variable $wp_query is designed for Paging; and it works within the default Loop and it requires some sleight of hand to make it work in custom Loops. This query actually $wp_query in order for paging work and you need to trick WordPress into thinking your custom query.
$temp = $wp_query;
$paged = ( get_query_var( ‘paged’ ) ) ? get_query_var( ‘paged’ ) : 1;
$wp_query = new WP_Query( ‘posts_per_page=5&paged=’.$paged );
while ($wp_query->have_posts() ) // Here the While loop start
: $wp_query->the_post(); // and then post call from the database
<h2> <a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a> </h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
The First step, store the original $wp_query variable into the temporary variable it is $temp. then, set $wp_query to null to completely flush and clean it. Sometimes it’s acceptable to overwrite a global variable value in the WordPress. Then set your new WP_Query object into the $wp_query variable then execute this by calling the object’s query() function to select posts for your custom Loop. You notice that the $paged variable added to the end of the query.
So this stores the current page, by using the get_query_var() function, the WordPress knows that how to display the navigation links on the page. Your navigation links for paging now displaying:
<div class=”alignleft”><?php previous_posts_link( ‘« Previous’ ); ?></div>
<div class=”alignright”><?php next_posts_link( ‘More »’ ); ?></div>
Finally, $wp_query back to its original value so you need it:
$wp_query = null;
$wp_query = $temp;
So this is your custom Loop will contain the proper pagination based on the content returned.