Fix pagination when using query_posts() in WordPress

Posted: July 1st, 2009 | Author: Henrie Media Inc. | Filed under: Web Applications | 3 Comments »

WordPress Crystal LogoIf you are a WordPress developer, or user, there may come a time where you will want to use the WordPress query_posts() function to retrieve your blog posts rather than the standard loop. For example, I wanted to exlude a category that contains all of my Twitter Tweets (I know, but run with in). So I put in the following code:

if (is_home()) {
query_posts(“cat=-52″);
}

The problem is that this also messed up the pagination of the page. To fix this issue I added this code:

if (is_home()) {
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
query_posts(“cat=-52&paged=$paged”);
}

Let me explain what I’ve added, and why.

query_posts() is a powerful function, but in this situation it has a flaw: it overrides nearly everything in the standard posts object query, including what the paged offset is. To get proper pagination with query_posts() we need to recreate it through the ‘paged’ parameter or query. Best way to do this is to ask WordPress for the “page” we happen to be on, and use that as our ‘paged’ value.

The $paged = line above uses what’s called a ternary operator to test whether the ‘paged’ query variable is available. If it is, $paged receives its value. If it isn’t, we assume we’re on the first page and assign it ’1′. Then we tell query_posts() what page we’re on with the addition of &paged=$paged.

Shazam! Fixed. Let me know if this helped you as well! Comments are always welcomed!

Print, Email, Share, Enjoy!
  • Print
  • email
  • Twitter
  • Facebook
  • Digg
  • MySpace
  • Mixx
  • del.icio.us
  • Technorati
  • StumbleUpon

3 Comments on “Fix pagination when using query_posts() in WordPress”

  1. 1 scribble30 said at 2:39 pm on January 18th, 2010:

    How would I get pagination to work with the following query?

    $cat,
    ‘showposts’ => $showposts,
    ‘caller_get_posts’ => $do_not_show_stickies
    );
    $my_query = new WP_Query($args);

    ?>

    have_posts() ) : ?>

    have_posts()) : $my_query->the_post(); ?>
    in_the_loop = true;
    ?>

  2. 2 Lewis said at 7:16 am on May 14th, 2010:

    Perfect. Thanks.

  3. 3 Philip Barron said at 3:03 pm on June 18th, 2010:

    Helped immensely, and taught me something, too. Thanks!

Leave a Reply