I can do something like the following with a standard category:

$query->set('category__not_in', $term_id);

But how do I do the same with a custom taxonomy term?

I'm using Wordpress 3.3.1 if it is relevant. Thank you. :)

  • Just a guess - perhaps I'm supposed to use something like '<custom taxonomy name>__not_in' instead? – rinogo Jan 18 '12 at 0:13
  • possible duplicate of And/Or Category Query – kaiser Jan 18 '12 at 1:11
  • Just search for tax_query if you want to build a new query. If you want to modify one, then re-build your initial query to use tax_query, then add a filter to posts_clauses and dump $pieces. Then just copy/paste your initial query from the dump, move it to the filter and use the default query (altered via the filter). This saves you a query per request as WP is doing one per default and every custom query is a new one. – kaiser Jan 18 '12 at 1:13
  • The problem is that I'm not the one who built the query. I'm trying to exclude a custom category from a particular query, intercepted via pre_get_posts(). So, I didn't build the query, and I can't build it from scratch. :P Ideas? – rinogo Jan 18 '12 at 1:17
  • "I'm not the one who built the query" ... What?! Do you have access to changing files or not? – kaiser Jan 18 '12 at 2:28

For what it's worth, I just gave up on the '__not_in' approach and went with the following somewhat sneaky solution:

//Create the exclusion rule
$new_tax_query = array(
        'taxonomy' => 'x_category',
        'field'    => 'slug',
        'terms'    => array('y-slug'),
        'operator' => 'NOT IN',

//If there is already a tax_query, 'AND' our new rule with the entire existing rule.
$tax_query = $query->get('tax_query');
if(!empty($tax_query)) {
    $new_tax_query = array(
        'relation' => 'AND',

// var_dump($new_tax_query);

$query->set('tax_query', $new_tax_query);
| improve this answer | |
  • $tax_query is an object that contains a nested array. You can't override the object with a nested array. – AlxVallejo Apr 17 '13 at 19:07
  • NOTE! AlxVallejo is wrong. $tax_query is not an object, $query is though (it's an instance of WP_Query): wordpress.stackexchange.com/questions/35196/… – its_me Nov 21 '13 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.