I use WordPress tax query and it looks like this:
Tax query
$args = array(
'post_type' => 'post',
'post__not_in' => array($post->ID),
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'color',
'terms' => $color_array,
'field' => 'slug',
),
array(
'taxonomy' => 'brand',
'terms' => $brand_array,
'field' => 'slug',
)
)
);
Then I try to dynamically add taxonomies with a foreach loop which gives me this array:
Taxonomy relation args array
array (size=2)
0 =>
array (size=3)
'taxonomy' => string 'color' (length=5)
'terms' =>
array (size=1)
0 => string 'pink' (length=4)
'field' => string 'slug' (length=4)
1 =>
array (size=3)
'taxonomy' => string 'brand' (length=11)
'terms' =>
array (size=2)
0 => string 'star' (length=15)
1 => string 'testar' (length=6)
'field' => string 'slug' (length=4)
foreach loop that creates array
Simplified.
$tax_relations = array();
foreach( $taxes as $tax ) {
$tax_relations[] = array(
'taxonomy' => $tax,
'terms' => $tax_array,
'field' => 'slug',
);
}
When adding the array to the tax query args it does not work:
Merge fails
This is what I do. Add the array I call $tax_relations.
$args = array(
'post_type' => 'post',
'post__not_in' => array($post->ID),
'tax_query' => array(
'relation' => 'OR', $tax_relations
)
);
What I figured out so far
It’s because of the keys. It adds 0 => array instead of just array. How is this solved?
You can do this like so:
Try this: