Exclude a WordPress custom taxonomy term from query_posts()

I’ve added the following code on one of my archive pages, just before the loop. I need this particular archive to display in alphabetical order, rather than chronological. This does what it’s supposed to do.

global $query_string;
$posts = query_posts($query_string . '&orderby=title&order=asc&posts_per_page=-1');

I also need it to exclude a particular taxonomy term. My taxonomy is called “company-type,” and I want it to exclude the term “featured.” I’m able to filter it to show ONLY that taxonomy term by adding &company-type=featured, but I need to accomplish the opposite.

Read More

Everything I’ve found that purports to accomplish this uses a very different syntax. I tried to match my current arguments to that syntax, but no luck, and I can’t figure out how it would fit into this example. The examples I’ve seen use the tax_query parameter, but I can’t get it to work with my code.

I know there are likely multiple ways to accomplish this, and I’ve read that using query_posts isn’t necessarily the best solution, but it’s the only one I’ve gotten to work so far. Can anyone help me?

Related posts

Leave a Reply

1 comment

  1. Okay, I got it working. I used a different syntax, which I had tried several times, but it hadn’t been working for me because I didn’t know how to include the original arguments from my $query_string with it.

    There’s a WordPress function called wp_parse_args that will get them into the same format for you. This is the code I ended up with. (I also switched to WP_Query instead of query_posts, now that I understand why it wasn’t working for me before.)

    global $query_string;
    
    $args = array( 
      'tax_query' =>  array (
        array(
          'taxonomy' => 'company-type', // My Custom Taxonomy
          'terms' => 'featured', // My Taxonomy Term that I wanted to exclude
          'field' => 'slug', // Whether I am passing term Slug or term ID
          'operator' => 'NOT IN', // Selection operator - use IN to include, NOT IN to exclude
        ),
      ),
      'posts_per_page' => -1,
      'orderby' => 'title',
      'order'=>'ASC'
    );
    
    $args = wp_parse_args( $query_string, $args );
    $query = new WP_Query( $args );