Posts archive index pagination in a static page custom query

When you perform a custom query such as this one, you have to do a bit of a “hack” to get pagination to work properly.

Change this:

<?php 
query_posts( "category_name=news&orderby=date&order=ASC&posts_per_page=2" ); 
?>

…to a WP_Query call:

<?php 
$news_query = new WP_Query( "category_name=news&orderby=date&order=ASC&posts_per_page=2" ); 
?>

And then you need to *move your custom query object into the $wp_query global`:

// Move $wp_query into a temp holder
$temp = $wp_query;
// Nullify the global object
$wp_query = null;
// Now move your custom query into the 
$wp_query = $news_query;

Then, update your loop initiation, from this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

…to this:

<?php if ( $news_query->have_posts() ) : while ( $news_query->have_posts() ) : $news_query->the_post(); ?>

This should cause the pagination to work as expected.

When you close your loop:

<?php endwhile; ?>
<?php endif; ?>

…just restore the original $wp_query global:

<?php endwhile; ?>
<?php endif; ?>
<?php $wp_query = $temp; ?>

And you should be good to go.

Leave a Comment