WordPress : Fixing Pagination on Custom Queries With query_posts

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 ),
));
?>
Source : http://www.rvoodoo.com/projects/wordpress/wordpress-tip-fixing-pagination-on-custom-queries-with-query_posts/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.