The Better Way to Get Custom WP_Query Loop Working with Pagination and WP-PageNavi

If you’re coming from my old post, here’s a more updated (and easier!) way to get your custom query working.

The key thing is not to mess with $wp_query. If we want a custom query, then it’s better to create a new variable for it.

<?php
// My custom query for the homepage of wplover.com
$wplover_home = new WP_Query('cat=-7&paged=' . $paged);
 
while ($wplover_home->have_posts()) : $wplover_home->the_post(); ?>
 
<h2 class="title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
 
<!-- the rest of the post stuff here -->
 
<?php 
endwhile;
if(function_exists('wp_pagenavi')) { 
	wp_pagenavi( array(
		'query' =>$wplover_home   
	)); 
}
?>

And that should do it. The important things are:

  • The paged parameter
  • The loop start now uses our query variable: $wplover_home->have_posts() and $wplover_home->the_post() instead of just have_posts() and the_post()
  • Inside the loop, though, we don’t need to use the query variable. It’s the_permalink() and the_title(), not $wplover_home->the_permalink() and $wplover_home->the_title().
  • PageNavi now has a ‘query’ parameter, enter our query variable’s name so the plugin detects it correctly.

This is the actual code running here, so I can confirm that it works, tested with version 2.74 of WP-PageNavi.

You may also like...

1 Response

  1. June 4, 2011

    […] .. ให้คลิกแทน) โดยควบกับปลั๊กอิน WP-PageNavi มาอ่านได้ตรงนี้เลย อันนี้คือตัวโค๊ดคร่าวๆ […]

css.php