Wordpress

WordPress Pagination in Custom Loop

If you use custom loops in WordPress you may run into pagination issues. Specifically, no matter what page you're on, only the first page's worth of posts are displayed. Here's a really quick solution to that problem using the query_posts() function.

I wrote an article a while back about using a static homepage for your WordPress blog. In that article I mentioned using a custom loop on this blog in the blog and tutorials sections. One problem you may run into when using a custom loop is that pagination doesn't work like you'd expect it to.In particular, you may notice that only the first page of posts are displayed no matter what page of posts you're trying to view. I often use WordPress as a general purpose CMS in client projects and so I use a lot of custom loops and run into this issue a lot. Here's the solution:

Update query_posts with the proper query vars

The solution to this problem is pretty simple. You need to tell WordPress to use the "paged" query variable in your custom loop, otherwise it's ignored. If you're using the query_posts function for your custom loop, the easiest way to do this is like so:

1
2
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('paged=' . $paged . '&cat=76'); // show posts in category 76 with pagination enabled

In this example, we first test to see if the "paged" query variable is set using the get_query_var function, which will return false if it's not set. If it is set, we'll set $paged equal to the value of that query variable and if not, we'll set it equal to 1.

Then we initialize our custom loop using the query_posts function by setting "paged" equal to our $paged variable so that WordPress grabs the current page from the URL and displays the appropriate list of posts for that page.

I'm also looping through the posts in category #76 in this example, which is only there for illustrative purposes. That's all there is to enabling pagination in custom WordPress loops.

John Crenshaw
John Crenshaw
President
UFO company founder. 15+ years experience in performance marketing.
Never miss an update
Get more training, case studies and ideas delivered directly to your inbox.
* We never share your personal info.
View our Privacy Policy.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Let’s make something great together
Let’s talk.

Get in touch and we’ll setup a quick call to discuss your needs, what we do, and figure out if we’re a good fit.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.