How to exclude specific tag from query_posts

Coding April 23, 2009 5 comments

On the upcoming theme I’m working on I needed to have a featured section on the left side, and normal posts on the right. Usually I would put the featured posts in a category, and excluded that from the normal posts. But for the end user, it is much easier to just tag the posts they want to be featured with “featured”. That way they don’t have to create a category called featured, select that in the options panel etc.

It isn’t so well documented,  so after talking to Adii we came up with the following code that does the job perfectly for the right hand side normal posts:

  1. get_var("SELECT term_ID FROM $wpdb->terms WHERE name=’featured’");                     
  2.  
  3. $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
  4. $args=array(
  5.    ‘tag__not_in’ => array($tag),
  6.    ‘paged’=>$paged,
  7.    );
  8. query_posts($args);
  9. ?>

The left side query is simple and just looks like this

  1.  
  2. <?php query_posts(‘tag=featured’); ?>
  3.  

Tags: , , ,

5 Responses

  1. iaan
    Apr 23, 2009

    Thanks for sharing Magnus (and Adii)!
    Is a line by line explanation too much to ask?


  2. Magnus
    Apr 23, 2009

    Here is a rundown:

    1: Get the ID for the tag “featured”

    3: This must be done to get pagination to work

    4: Load the arguments for the query into $arg

    5: Parameter to tell the query to skip any posts with the ID we found on line 1

    6: For pagination to work

    8: The query itself


  3. [...] How to exclude specific tag from query_posts – as I’ve noticed from working on numerous themes at WPCoder, having “featured” posts is really a popular feature these days. The easiest way to do this is probably to tag posts with “featured” instead of having a dedicated category, so here’s how to exclude those posts from the rest of the loops on your site. [Link] [...]


  4. Banago
    Apr 30, 2009

    Great tip. I love to work with WP queries and this one will expand my repertoire. Thanks for sharing!


  5. [...] How to exclude specific tag from query_posts – as I’ve noticed from working on numerous themes at WPCoder, having “featured” posts is really a popular feature these days. The easiest way to do this is probably to tag posts with “featured” instead of having a dedicated category, so here’s how to exclude those posts from the rest of the loops on your site. [Link] [...]


Magnus Jepson

Hello! I’m Magnus Jepson, a web designer and co-founder of WooThemes, from Norway. This is my personal feed site where you can get updates of what I’m up to.

Drop me a line!

If you’d like to tell me about some exciting stuff or just say hello, my e-mail is magnus@jepson.no