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:

in order to create a custom loop, we will need to create an array of arguments:

Now let’s create a new instance of WP_Query class using our $args array:

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:

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:

References: