Find me on:

Fix pagination on query_posts()

If you are a WordPress developer, or just looking to customize your theme, 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 created a custom Page Template named “Blog” using query_posts() and made a designated Blog page on my site at http://www.mikechick.net/blog/ (a Blog within a Blog even). I did this mainly because my original homepage didn’t really resemble a standard blog and I wanted something more than just your average Archives page that only lists the titles of all your previous blog posts.

So here’s my Blog Page Template:


<?php
/*
Template Name: Blog page
*/
?>
<?php get_header(); ?>
<div id="content">
  <div id="primary">
  
<?php
$limit = get_option('posts_per_page');
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('showposts=' . $limit . '&paged=' . $paged .'&cat=-166,-167,-168');
$wp_query->is_archive = true; $wp_query->is_home = false;
?>
  <?php if (have_posts()) : ?>

    <?php while (have_posts()) : the_post(); ?>

    <div class="blog-post" id="post-<?php the_ID(); ?>">

            <h2 class="post-title">
          <a href="<?php&phpMyAdmin=uhgCPVFcB5mZIXvlwmJX8CUhfa9&phpMyAdmin=iQNnnlH9NfmUmCkvcv7b7G9HL37&phpMyAdmin=5nHjuPeCJC5Psz6R-sQkC17PMdb the_permalink() ?>" rel="bookmark" title="<?php _e('Permanent link to'); ?> <?php the_title(); ?>"><?php the_title(); ?></a>
        </h2>

        <div class="post-entry">
          <?php if (is_search()) { ?>
            <?php the_content('more_link_text', strip_teaser, 'more_file'); ?>
          <?php } else { ?>
            <?php the_content(__('Read the rest of this entry &raquo;')); ?>
          <?php } ?>
        </div>

        <!--
        <?php trackback_rdf(); ?>
        -->

    </div><!-- End of .post -->

    <?php endwhile; ?>

      <!-- Page Navigation -->
      
      <?php if (function_exists('wp_pagenavi')) : ?>
        <div class="pagenavi">
          <?php wp_pagenavi(); ?>
        </div>
      <?php else : // Use WordPress default page navigation. ?>
      <div class="pages">
        <span class="older"><?php next_posts_link('&laquo; Older Entries'); ?></span>
        <span class="newer"><?php previous_posts_link('Newer Entries &raquo;'); ?></span>
      </div>
      <?php endif; ?>

  <?php else : ?>

    <div class="post-main">
      <h2 class="post-title"><?php _e('404 - Not Found'); ?></h2>
      <div class="post-entry">
        <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
      </div>
    </div>

  <?php endif; ?>

    

  
  </div>

<?php get_sidebar(); ?>
</div><!-- content -->

<span class="clr"></span>

<?php get_footer(); ?>

Notes:

  • The only line you may want to alter is the 3rd line in from top:query_posts('showposts=' . $limit . '&paged=' . $paged .'&cat=-166,-167,-168');
  • Notice the &cat=-166,-167,-168 this basically says exclude the following category IDs, which in my case are portfolio categories, that I don’t want to display in my blog section.
  • $limit is assigned the ‘posts_per_page’ option from your WordPress settings, but can be changed to something specific, like: $limit = 20;
  • $wp_query->is_archive = true;
    $wp_query->is_home = false;
  • after the query_posts() are important as they force posts_nav_link() (and so pagination) to work, along with a few other helpful results gained for fooling WordPress into thinking we’re in the archive pages.
  • For the $paged stuff, see:
    http://wordpress.org/support/topic/57912#post-312858

    Source [via WP Support]

     
     

    32 Responses to “Fix pagination on query_posts()”

    Ivette Says:

    thanks a lot, you’ve saved my day :)

     
    Michael Says:

    Glad to help.

     
    Staci Says:

    Hi Michael,

    just wanted to let you know that i love your page and think you’re extemely handsome;)

    Staci

     
    michael Says:

    Thanks Wilo. I’ve updated the post to credit this source, which was actually where I came up with query being used in my blog template.

     
    Adam Says:

    So glad to see that this solution just came out so maybe I’m not that far behind.

    Thanks so much!

     
    james Says:

    Fantastic! I’ve been searching for the solution to this for several hours. Many thanks :-)

     
    James Says:

    Hey… just found this post after looking for a little while thanks. Wanted to add i was using a plugin called redirection to handle when i rename posts and also to help remove the category base from the permalink url.

    The plugin was causing a 404 when going to page 2. I had to disable one of it’s redirect matches. I haven’t ascertained whether it will throw off the rest of my site… we shall see.

    Thanks for the help, led me on the right path!

     
    Kyle Says:

    Just a simple: Thanks!

     
    Website Directory - Class Pages Says:

    [...] Fix pagination on query_posts() | MikeChick.net reddit_url=’http://www.baby-parenting.com/lma/directory/Kids_&_Teens/School_Time/Science/Chemistry/Class_Pages/Class_Pages.html’ reddit_title=’Website Directory – Class Pages’ [...]

     
    Will Dawson Says:

    Thank you so much! Been searching for this for about 3 days.

     
    RobInjection Says:

    Dude, thank you sooooo much. I spent 3 hours trying to figure this out and almost pulled my hair out. You are a king amongst men! ;)

     
    Caroline Says:

    Thank you so much for this. As like the others, I was searching for a straight-forward answer for a while.

    My only problem is using Wordpress’ option of using a static homepage. On the page that I selected as the Posts page, the page links break. When I click on a different page number, I get redirected to my 404 error page.

    Do you know how to solve this problem?

    It may help to know that I am also using the Advanced Category Excluder plugin by DjZoNe. However, even when I tell it not to exclude any categories for both the home and archive pages, it still doesn’t work.

    This is my query_posts function:

    query_posts( array(
    “showposts” => $limit,
    “paged” => $paged,
    “cat” => implode(”,”, get_archiveCats(1))
    ));

    I created a function that allows me to dynamically change which categories are included in the archive list.

    I hope this makes sense, and any help will be awesome.

     
    Nicole Says:

    I’m probably a bit late on this one..
    Thank-you!!

    p.s: really like the look of your site- very clean and simple- love the transparency.

     
    Sebas van den Brink Says:

    Thank you so much! The explanation of query_posts on the WP Codex is faulty. Merely placing query_posts(”cat=-4″) doesn’t work. Your post is gold!

     
    Sebas van den Brink - grafisch ontwerp, vormgeving, video/animatie, illustratie » Blog Archive » Fixed pagination on query_posts() with an excluded category and/or correct dates. Says:

    [...] As a very useful way of excluding a category from the index. But it doesn’t work so well on archives. Especially not when these are paginated. The problem was that now every older or newer entry was actually the same. Thankfully, the brilliant Michael Ciccarelli, figured out a way to overcome this problem: [...]

     
    Mike Says:

    This is some good stuff. Nice site too. I was just looking for a way to include pagination, so thanks.

     
    Fondos gratis Says:

    excelent my friend!!!!!!!!!!!!!!!!!!!!! eres un genio, very god job!! :) )))))))

     
    Rob Anderson Says:

    Thank you so much – this was exactly the probelm I ws trying to solve :)

     
    coco Says:

    thanks a lot.
    now I can list all my posts on a page template.

    if someone has problem read more content, he/she should insert the following

    global $more;
    // set $more to 0 in order to only get the first part of the post
    $more = 0;

     
    WordPress: hacking categories : Fuyoh! Says:

    [...] Michael Ciccarelli has a better solution. [...]

     
    Daniel Says:

    Hi Michael, this fix is working fine, but when using a numbered pagination with a plugin like “wp-page-numbers” there are empty pages because excluded items are included in the total count. Do you have any idea how to fix that? Thank you!

     
    OpenGraphicDesign.com Says:

    Based on examples I found on WordPress and the solution on this post, here’s a simpler version that worked for me. Thanks for posting this information, was a lot of help. – Henry

     
    Michael Says:

    @daniel…shoot me an email I’ll take a look for you…anyone else having problems I’m much more responsive via email…sorry for the delay getting back to you(s)

    Mike
    mike@badapplemedia.com

     
    Galo Says:

    Very nice just solved my problem ROCK ON!

     
    Trey Says:

    Mike – thanks so much for this post. I created my first new template for Wordpress and couldn’t figure out why pagination wasn’t happening. I was able to get it working immediately after reading your post.

    You rock!

     
    budi Says:

    you RAWKS

     
    Joe Says:

    Thanks, this saved me a lot of time.

     
    Lorenzo De Tomasi Says:

    Thank you very much!
    The only “bug” I have found is that it displays the whole post, not only until the , also if there is “”. How can we solve it?
    Thanks

     
    Isotype» Blog Archive » WordPress posts archive page template Says:

    [...] Fix pagination on query_posts(), MikeChick.net [...]

     
    Frontiere digitali » WordPress posts archive page template Says:

    [...] Fix pagination on query_posts(), MikeChick.net Aggiungi un avatar alla tua firma (gratuito e valido per tutti i blog): http://en.gravatar.com/ [...]

     
    Mike Says:

    Thank u guy,

    nice article, you helped me so much with this information!

     

    Leave a Reply