Wp_pagenavi working with WP_Query
If you’re creating a custom template (let’s say for categories), then it is likely that you will have to use WP_Query class. But what if you want to use WP-PageNavi plugin in order to create pagination on the website? On one of the websites I’ve worked on recently, that’s exactly what I had to do, since the theme was using wp_pagenavi in order to show pagination. Since this may be a common thing to implement, let me give you the code on how I did it.
First of all, you will need to add “paged” parameter to your custom query:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
in order to create a custom loop, we will need to create an array of arguments:
$args = array (
'post_type' => 'post',
'cat' => '53',
'paged' => $paged,
'posts_per_page' => '10'
);
Now let’s create a new instance of WP_Query class using our $args array:
$query = new WP_Query( $args );
Now we have everything we need for our custom loop to work. But before all, let’s see that little tweak that makes wp_pagenavi working – it is adding our $query into pagenavi function:
if(function_exists('wp_pagenavi'))
{
wp_pagenavi( array( 'query' => $query ) );
}
And now it works perfectly and will not display same posts on every page.
So this is how the whole code would look like – you’re free to modify whatever appears within the loop:
'post',
'cat' => '53',
'paged' => $paged,
'posts_per_page' => '10',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
get_template_part('parts/blogloop');
}
if(function_exists('wp_pagenavi'))
{
wp_pagenavi( array( 'query' => $query ) );
}
wp_reset_postdata();
} else {
echo 'no posts here';
}
?>
References:
WP-PageNavi
Class Reference/WP Query
WP_Query Generator @ http://generatewp.com/
Pagination