wp query with multiple taxonomy?

You can have more than two. You could have as many as you like but you may have performance penalties if you try to use too many. I’d expect this to be true especially if you use an OR relationship.

See the following for a way to create your tax_query array dynamically.

https://wordpress.stackexchange.com/a/97444/21376

To adapt that to your circumstances just associate each term with its taxonomy.

$def = array(
    'field' => 'slug',
    'operator' => 'NOT IN'
);

$cities = array(
    'boston' => 'tax_city',
    'chicago'  => 'tax_city',
    'texas'  => 'tax_state',
    'california'  => 'tax_state'
);

$args = array('relation' => 'OR');

foreach ($cities as $term => $tax) {
  $args[] = wp_parse_args(
    array(
      'taxonomy'=>$tax,
      'terms'=>$term
    ),
    $def
  );
}
print_r($args); 

You could do the same with nested Loops.

$cities = array(
  'tax_city' => array(
    'boston',
    'chicago'
  ),
  'tax_state' => array(
    'texas',
    'california'
   )
);

foreach ($cities as $tax => $terms) {
  foreach ($terms as $term) {
    $args[] = wp_parse_args(
      array(
        'taxonomy'=>$tax,
        'terms'=>$term
      ),
      $def
    );
  }
}
print_r($args);

Leave a Comment