WP_Query and Paging
Recently I needed to build a custom WordPress query to display child pages of the current parent page that included the ability to cycle through pages if there were more child pages that would fit on one page – in my case 9.
I started by using WordPress query_posts but came across a few articles that warned against using this. Apparently it should only be used when you want to modify the main query of a page and it should not be used with other queries. While I will probably only use this one query, it looks like it’s safer to just use WP_Query.
So I decided to use WP_query. This worked fine at first until I realised that the pagination that was previously working with query_posts was no longer working.
In order to get WordPress pagination to work with WP_Query I had to trick WordPress into thinking that the custom query was $wp_query because paging is currently designed to work only with the $wp_query global variable. It works in the default loop but not in a custom loop.
Below is the code I used, hope this helps!
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$parent = $post->ID; /* Show child pages - Delete if not needed */
$args=array(
/* Add whatever you need here - see http://codex.wordpress.org/Class_Reference/WP_Query */
'post_parent' => $parent, /* Show child pages - Delete if not needed */
'posts_per_page' => 9,
'post_type' => 'page',
'order' => 'desc',
'paged' => $paged,
);
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
?>
<?php /* LOOP GOES HERE */ ?>
<?php endwhile; endif; ?>
<div class="page-nav">
<div class="nav-previous"><?php next_posts_link('<< Next'); ?></div>
<div class="nav-next"><?php previous_posts_link('Back >>'); ?></div>
</div>
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
NOTE!
When using pagination on a home page template replace this:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
with this:
$paged = (get_query_var('page')) ? get_query_var('page') : 1;



