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:
1 |
$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:
1 2 3 4 5 6 |
$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:
1 |
$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:
1 2 3 4 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array ( 'post_type' => '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: