Die query_posts()! Die!

For some it’s well known that query_posts() should never be used, but I still see it dotted around here and there, so this is my attempt to help kill it off.

Every time you use query_posts() a kitten does

Every time you use query_posts() a kitten dies. Photo by Brian Scott.

I’m going to keep this post as non-technical as I can. The ins and outs of query_posts() is best left to this video by Andrew Nacin:

Instead, I’m going to talk about what you should be using instead of query_posts() and some of the nuances of pre_get_posts that could land you in hot water. But first…

Why Is query_posts() So Bad?

Mainly, for two reasons:

Query Then Template

It’s bad because runs against WordPress’ handling of website url to page load. query_posts() is directly linked with the main query – this isn’t a handy-wavy notion – it’s a real (global) object: $wp_query. This query is formed from the url of the current page and determines what WordPress displays. But importantly WordPress performs the query first and then chooses the appropriate template.

However, when you use query_posts() in a template file you doing the opposite – you’re trying set the ‘main query’ based on the template used. This can lead to pagination issues and 404s.

It’s Linked to the Main Query

Secondly, the main query is what WordPress thinks is the main content of what it’s displaying. When you change that via query_posts() to display a list of related posts, for example, you end up changing what WordPress thinks it’s displaying. You may end up displaying the comments for the last post on that ‘related post’ section and not the page being viewed.

What’s the solution?

Nice and easy:

1. Secondary queries

For displaying posts in the sidebar / beneath content – or just generally performing ‘secondary queries’ – that is queries that does not related to the main content of the page:

<ul>
  <?php
  global $post;
  $posts = get_posts( array( 'numberposts' => 5, 'category' => 3 ) );
  if( $posts ):
     foreach( $posts as $post ) :   
        setup_postdata($post); ?>

       <li>
          <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
       </li>

     <?php endforeach; 
     wp_reset_postdata(); 
   endif; ?>
</ul>

or

<ul>
  <?php
  $my_query = new WP_Query( array( 'numberposts' => 5, 'category' => 3 ) );
  if( $my_query->have_posts() ):
     while( $my_query->have_posts() ):
        $my_query->the_post(); ?>

       <li>
          <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
       </li>

     <?php endwhile; 
     wp_reset_postdata(); 
   endif; ?>
</ul>

both work fine.

Note the wp_reset_postdata(); – this is important so WordPress doesn’t confuse the last post in your secondary loop for the post associated with the current page!

2. Altering the Main Query

If you wish to alter the main query, for instance to exclude a category from the search page, then the action pre_get_posts (yes it’s an action not a filter).

add_action('pre_get_posts','my_alter_query');
function my_alter_query( $query ){

      //Is $query the main query? And is the main query for a search
      if( $query->is_main_query() && is_search() ){
        //Do something to main query

        //Exclude category with ID 12.
        $query->set( 'cat', '-12' );
      }
}

That snippet should live in a plug-in, though it would also work in your theme’s functions.php.

But before you start tinkering with queries via pre_get_posts, take note of the health warnings…

pre_get_posts is triggered for every query

This includes admin and non-admin queries, for posts, navigation menu items (yes they’re post types), related post widgets. The lot. That is why if you only mean to alter the main query you check the conditional $query->is_main_query().

But this makes it incredibly powerful. Now I can not just alter the main query, but I can alter any query for a particular post type:

add_action('pre_get_posts','my_alter_query');
function my_alter_query( $query ){

      $pt = $query->get( 'post_type' );

      if( 'event' == $pt || ( is_array( $pt ) && array( 'event' == $pt )  ){                  
         //Do something to queries which are for events only
      }

      if( 'event' == $pt || ( is_array( $pt ) && in_array( 'event', $pt )  ){                  
         //Do something to queries which include events
      }

      if( $query->is_tax( 'event-category' )  ){                  
         //Is the query for an event category
      }

}

Take away point: pre_get_posts is not just for the ‘main query’

Functions vs Method

You’ll note that in the above example I used the method $query->is_main_query() and the function is_search(). What’s the difference? Quite a lot:

Functions = main query, Methods = current query

Conditional functions such as is_search() and is_tax() are wrappers for

 global $wp_query; 
 $wp_query->is_search();
 $wp_query->is_tax();

That is they apply to the ‘main query’. But since $query passed in pre_get_posts is not the always the main query, using a methods or functions are – in general – not the same thing. You’ll need to think about which you need to use: should the conditional apply to the passed $query object, or the main query object?

Lastly, Tom McFarlin has recently written a couple of articles on query_posts() and pre_get_posts. I recommend you check them out:

And also Rarst’s epic answer on WPSE: When should you use WP_Query vs query_posts() vs get_posts()?

One thought on “Die query_posts()! Die!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>