WordPress Custom Query Pagination

Development,Snippets,WordPress

You’re here because you have a custom WP_Query and loop but you’re not content. You also want nice numbered links to results pages. Maybe you already tried the example in the WordPress codex, or even Nick Salloum’s in depth and informative walkthrough, “Custom WordPress Loop With Pagination.” I highly recommend you check out both of those because this is just a quick improvement on Nick’s outstanding article.

I like to ensure everything gets nicely paginated, even my search results. The problem with Nick’s eloquent solution is that it doesn’t play well with URL parameters. The WordPress default search behavior appends ?s=search+term to your search URLs. Unfortunately the $base and $format in Nick’s paginate_links() function don’t account for URL parameters, so we end up with incorrect links to pages like https://example.dev/?s=search+termpage/2. This is wrong and will result in a 404 error when clicked; we want https://example.dev/page/2/?s=search+term instead. Fortunately, there’s a straightforward fix using some logic from WordPress’s own get_pagenum_link() function and a regular expression.

We simply need to check the results page link URLs for parameters. If they have URL parameters then we need to make sure they get appended to the end of the paged link URLs. Line 14 below is where that all takes place.

It’s only mentioned briefly on the codex but '%_%' gets replaced by the $format argument and '%#%' ultimately gets replaced by the page number. I struggled with this a bit at first but it all makes sense.

I hope this helps someone else out there achieve maximum precision and consistency in your WordPress custom query pagination.


Leave a Comment