Excluding a custom taxonomy from WP_Query

Jul 15 2012 0 Comments

While working on a project where I need to exclude a custom taxonomy from my output, I found myself scratching my head. I assumed since I exclude normal WordPress categories by using something like this:

$query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'category' => -34 );

that I would do something similar for my own custom taxonomy. In this case it’s ‘news_category’ so I ended with up this:

$query = new WP_Query( array( 'post_type' => 'news', 'post_status' => 'publish', 'news_category' => -34 );

That didn’t give me the results I expected so I checked the codex and didn’t see anything. I also tried category__not_in, news_category__not_in and had the same luck. So after putting my google-fu to good use I ran across someone with the same issue on the WordPress Answers StackExchange (http://wordpress.stackexchange.com/questions/51797/exclude-posts-with-custom-taxonomy) where I found out about tax_query.

So I go back to the codex, ctrl+f and low and behold, I’m blind. It’s right there under Multiple Taxonomy Handling in the Taxonomy section (http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters).

Here’s the query I ended up with that does what I want

$q = new wp_Query( array(
    'post_type' => 'news',
    'post_status' => 'publish',
    'posts_per_page' => 5,
    'orderby' => 'date',
    'order' => 'desc',
    'tax_query' => array(
        'relation' => 'AND',
            'taxonomy' => 'news_category',
            'field' => 'id',
            'terms' => $press_cat,
            'operator' => 'NOT IN'
) );

Leave a Reply

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