NOTE: An update to this tutorial now lives over on VoodooPress. It’s got the same code examples, slightly cleaned up. But the explanation is a little more lengthy, in case you want to understand what is going on.
Here’s something I run across frequently on the WordPress Forums. Pagination not properly working on custom pages using query_posts. Well, the solution is quite simple. You have to account for pagination anytime you use a custom query. And you do that in the query_posts line. Here’s an example of how that is done.
First off, custom queries are good for calling or excluding certain posts to a page. Lets say we want to display 5 posts per page from category 10. The best place to learn how to do this is the Codex. You would probably start after reading that article like this:
<?php query_posts('posts_per_page=5&cat=10'); ?>
Now technically this would be proper, and it would get you the results you are after, but there would be no pagination. So if you had many posts and were trying to go to the next page, the same posts would still show. Here’s how to fix that. First off, I like to put all my args for query_posts into an array, it’s so much simpler to look at and organize. So the above as an array would be:
<?php query_posts( array ( 'posts_per_page' => 5, 'cat' => '10', )); ?>
And that would work the same. But it’s more organized to me, and so much easier to add more items. Now the answer to our problem. We will take that above query array and get pagination working.
<?php query_posts( array( 'posts_per_page' => 5, 'cat' => '10', 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ), )); ?>
And there we have it! I think that’s pretty simple. Always include pagination within your custom query and you’ll be good to go!
UPDATE: Thanks to a reader, and a little scan through the codex, it looks like we may need to update the code above.
<?php query_posts( array( 'posts_per_page' => 5, 'cat' => '10', 'paged' => ( get_query_var('page') ? get_query_var('page') : 1 ), )); ?>
Looks like the way to do things since WP version 3.0.2. You can read about it in the codex. All we did was change the get_query_var from paged, to page.