WordPress Pagination

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:

$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.