If you have been working with WordPress for a while, no doubt you have been stumped on how to handle custom post type pagination.
“WordPress offers built-in functionality for navigating through posts. Theme developers can use simple links or numbered pagination to indicate the previous page or the next page in a given sequence.”Codex
The problem is, this pagination built into WordPress does not work on custom post types, it only works using standard posts.
I’m going to be the first to admit that I was really stuck on this one. I went through various tutorials online including paginate links, wpza and even the wpsmith article to build a plugin in composer using custom rewrite URLs. None of them worked.
After much trial and error, I am going to share the code with you for how I got CPT pagination running successfully on my project.
- Go to your functions file and using the template redirect hook, and unhook redirect_canonical.
2. Next we are going to declare our pagination function and use the paged parameter within our wp_query loop. We are also going to remove our redirect canonical and template redirect filters. The gist is below if you’d like to copy:
3. Next, we need to alter the custom query in our custom post type archive page. For practical purposes I have called this template archive-template but if your custom post type category is moves you would call this archive-movies.php.
4. after your loop/endif statement, call in the pagination function using a div class of pagination
5. Finally, we need to jazz it up with some CSS. Feel free to change the hex colours and styles as required
And that is is my friends! Now when you click on page 2, instead of showing the URL of /page/2 and refreshing the first page, your custom post type template will calculate how many pages you have based on your max posts per page, and paginate through them.
I really hope this saves someone some time, and they don’t get stuck on this as I did.
Alpha Omega Digital is a WordPress agency based in Melbourne, Australia but also services clients from Sydney, Brisbane, Newcastle, Perth, Adelaide, Darwin and Hobart. Have a project in mind? Contact me here.