Here:
$search_values['tax_query'] = array (
You’re resetting the value of tax_query
for every item in the foreach
loop.
It’s also being set to an invalid value:
Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays). This construct allows you to query multiple taxonomies by using the
relation
parameter in the first (outer) array to describe the boolean relationship between the taxonomy arrays.
So to build up a tax_query
of multiple arrays, you need to set $search_values['tax_query']
to an empty array, then append each array:
if( ! empty( $_GET['ct_lifestyle'] ) ) {
$ct_lifestyle = (array) $_GET['ct_lifestyle'];
$search_values['tax_query'] = array();
foreach ($ct_lifestyle as $lifestyle):
$search_values['tax_query'][] = array (
'taxonomy' => 'lifestyle',
'field' => 'slug',
'terms' => $lifestyle,
);
endforeach;
}
Also note this bit:
$ct_lifestyle = (array) $_GET['ct_lifestyle'];
Casting it as an array means that if only one ct_lifestyle
parameter is present then it will get put into an array with a single item. That way your foreach
will still work without you having to handle a single item differently.
That code has the assumption that you want the query to match posts that have all the given ‘lifestyes’. This is why I removed the IN
operator
from your code. If you want to match posts that have any of the given lifestyles you can skip the foreach
and just pass the array into the one tax_query
:
if( ! empty( $_GET['ct_lifestyle'] ) ) {
$ct_lifestyle = (array) $_GET['ct_lifestyle'];
$search_values['tax_query'] = array(
array(
'taxonomy' => 'lifestyle',
'field' => 'slug',
'terms' => $ct_lifestyle,
'operator' => 'IN',
)
);
}