WordPress query_posts with pagination
This is probably the first issue I stumbled upon ever since I started working with WordPress; which is surprising because I really expected hacking in PHP templates to be much harder and error prone (but more on that in following articles).
The issue comes up when you want to display posts based on some specific criteria, for example listing the most recent posts from all but one category. There’s an amazing query_posts().
When I first realized that I need to display only something and not everything on the main page, I got a little angry, because I expected I will have to code all the stuff myself, but WordPress surprisingly offered a very easy solution.
Specifically, I needed to exclude a category #5, and all that needs to be done is call query_posts() right before the main loop.
<?php query_posts('cat=-5&posts_per_page=3') ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
// blah blah usual stuff
Note the cat=-5, which says I want everything EXCEPT for the category #5.
Now there are two downsides of doing this. First, the query will persist even if you have multiple loops, so you need to reset it back by calling wp_reset_query() after the main loop, which isn’t such a big deal.
Another thing that stops working though is the use of next_posts_link() and previous_posts_link(), because once you call query_posts() WordPress won’t automatically apply the page parameter; you will have to pass it manually.
<?php query_posts('cat=-5&posts_per_page=3&paged=' . get_query_var('paged') ); ?>
Yes it is very simple, but also very easy to forget. The bottom line is every time you call query_posts(), be sure to check your pagination.
