Custom WP_query and Pagination

Unfortunately to this day there isn’t a lot of good information about pagination with a custom post type wp_query. It’s very surprising considering the endless uses for custom post types (CPT) and how long they have been past of WordPress. Additionally of the information out there about this a lot of it is unclear or in my opinion not the best advice. Anyway, moving on, I am here today to hopefully help someone out with this.

There are 3 ways that I would suggest to tackle the problem, though I strongly recommend option #1. Alright, time to dig in!

Option 1 – use max_num_pages variable

// Loop Code Here…

You’ll see above, a slightly different format for ‘previous_posts_link’ and ‘next_posts_link’ which now access the ‘max_num_pages’ variable. Be sure to use your own query variable name when accessing ‘max_num_pages’. Notice I use $cpt_query since that is the variable for my query example.

Option 2 – temporarily use the $wp_query variable for your loop query

This is what a lot of folks recommend, but be careful to asign the $wp_query variable to a temp variable and re-assign it or you will run in to all kinds of troubles. Which is why I recommend Option #1. As noted on CSS Tricks, you can do something like this:

Just as another option what you can do instead is use the WP-pagenavi plugin, and setup your query as in Option #1. But make one change in the code, remove everything within the “nav” element and replace with this function, once you have installed the plugin. So you’ll end with:

Please let me know if this helped, or how you like to handle pagination for CPTs!