1

I am stuck with this. Maybe its simple, maybe its not. But there goes.

I understand that the standard way of querying multiple taxonomies in wordpress is using the method described here.

https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

However, this way only allows for "hardcoded" taxonomies.

What I'd like to achieve is run the query for multiple variable taxonomies.

So assume I have my array of taxonomies via:

$taxes = get_taxonomies( array('public' => true ) , 'names', 'and' );

Trying to pass the $taxes variable directly does not work as 'taxonomy' does not accept arrays. e.g.

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => $taxes,
            'field'    => 'term_id',
            'terms'    => $terms,
        ),
    ),
);
$query = new WP_Query( $args );

Therefore I tried to work around this by first attempting:

foreach ($taxes as $tax) {
    $the_taxes[] = array (  
        'taxonomy' => $tax,
        'field'    => 'term_id',
        'terms'    => $terms,
    );
}

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
    'relation' => 'OR',
    $the_taxes                  
    ),
);

This did not work, I guess because $the_taxes variable is itself an array of arrays. I even tried to give it a stripped version of the array output without the array() wrap to imitate exactly the same output as if I had followed the standard wordpress way of hardcoding the taxonomies to be queried.

$the_other_taxes = substr(print_r($the_taxes,true),19,-2);
$args = array(
    'post_type' => 'post',
    'tax_query' => array(
    'relation' => 'OR',
        $the_other_taxes                    
    ),
);

Still no luck..

Is there a workaround for this problem? Am I missing something obvious?

Thanks a lot, Harry

1
  • Maybe declare it like this: $the_taxes = array( 'relation' => 'OR' ) and keep your foreach the same, then just 'tax_query' => $the_taxes
    – Howdy_McGee
    Commented Mar 4, 2016 at 21:35

1 Answer 1

4

tax_query requires an array of arrays, and $the_taxes is an array of arrays, you've already got 99% of your answer.

foreach ($taxes as $tax) {
    $the_taxes[] = array (  
        'taxonomy' => $tax,
        'field'    => 'term_id',
        'terms'    => $terms,
    );
}

$the_taxes['relation'] = 'OR';

$args = array(
    'post_type' => 'post',
    'tax_query' => $the_taxes,
);
1
  • That was quick and spot on!!! Thanks a lot for making it THAT simple ;-)
    – harman
    Commented Mar 4, 2016 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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