How to get Custom WP_Query Loop Working with Pagination and WP-PageNavi
Update May 6th, 2011: This article is now outdated, please read this one instead for a more updated way get your custom query working with pagination and PageNavi.
For this current redesign of wplover (have you seen it? come take a look!) I’m using a custom loop in the index page to remove all posts under “Links” category from the main content area. Now the most common problem with WP_Query-based custom loops is that it screws up pagination. No problem, we have this WBLT post to the rescue, and now my code looks like this:
<?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query('cat=-6&paged=' . $paged); // don't show posts from category ID 6, a.k.a Links while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <?php // the usual post-displaying codes here ?> <?php endwhile; $wp_query = null; $wp_query = $temp; ?> |
One more thing to add is that I’m also using the WP-PageNavi plugin to show custom page navigation after the posts. After messing around with the code a bit, I find that to get the plugin working, the plugin function call needs to be placed right after endwhile; and before $wp_query = null, like so:
<?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query('cat=-6&paged=' . $paged); while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <?php // the usual post-displaying codes here ?> <?php endwhile; if(function_exists('wp_pagenavi')) { wp_pagenavi(); } $wp_query = null; $wp_query = $temp; ?> |
Placing the plugin call there will result in the correct pagination. You’ll get funky paging errors if it’s placed after the whole $wp_query variable swapping in the end.