Showing or hiding posts based on tags

Writing Taexalia's new theme this week, I needed a way to exclude posts from her home page based on tags. We didn't want Twitter archive posts to show up in the "featured" postition. Often in this kind of situation, the posts you want to exclude will be from a specific category, but this time, they weren't: they were in a category with other posts that she *would* want to have featured. The thing that distinguished her Twitter archive posts was a set of tags. Was it possible, I wondered, to exclude posts from query results based on tags?

A little judicious Googling led me to this thread, and tag__not_in (By the way, that's two underscores after 'tag'.)

query_posts is used to modify the main loop; it needs to sit outside the loop itself (i.e. before if(have_posts()) etc.) To exclude posts with any of the tags alpha, beta or gamma, use:


query_posts(array('tag__not_in' => array('alpha','beta', 'gamma'));

Or perhaps you want to *only* show posts with those tags? tag__in finds posts with any one (or more) of the specified tags; tag__and finds posts which have *all* of the specified tags. So a post with just the tags alpha and beta would show up with

query_posts(array('tag__in' => array('alpha','beta', 'gamma'));

but not with

query_posts(array('tag__and' => array('alpha','beta', 'gamma'));

If you're only interested in one tag, you can use a slightly simpler way of doing things:

query_posts('tag=alpha');

finds posts with the tag alpha.

Share this post:
  • email
  • del.icio.us
  • Facebook
  • FriendFeed
  • LinkedIn
  • StumbleUpon
  • Tumblr
  • Twitter

Tags: , , ,

Posted by Sue on June 8, 2009 in WordPress.

One comment to "Showing or hiding posts based on tags"

  1. Gaspard wrote:

    Hi, this is really interesting! This might be able to help me with a problem i'm having. In my single.php file, I want to hide the sidebar based on Tags.

    Currently, to call the sidebar, this code is present:

    ?php get_sidebar() ?>

    How can I modify this line so if Tag ISN'T equal to alpha, then show sidebar? Which of course will show sidebar for all other tags.

    Thanks so much!
    Gaspard

Leave a Reply