Tax Query – How do I properly merge the array into ‘tax_query’ so I only get the results for all filters instead of any

I am building a search and filter page. I have come upon a problem. I have 9 filters. The user will select none, one, or any number of them at a time. I’m trying to avoid writing endless combinations of questions to satisfy each of those options.

I only want to show the results of all the filters together. This code works fine:

$taxquery= array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => 'filter1',
        'operator' => 'IN',
    ),
    array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => 'filter2',
        'operator' => 'IN',
    ),
    array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => 'filter3',
        'operator' => 'IN',
    ),
);

I really want to do something like this. I collect values [GET] parameter first.

$mergedarrays= [];
if(isset($getfilter1result)){
$filter1= array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => 'filter1',
        'operator' => 'IN',
    );
array_merge($mergedarrays, $filter1);
}
if(isset($getfilter2result)){
$filter2= array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => 'filter2',
        'operator' => 'IN',
    );
array_merge($mergedarrays, $filter2);
}
if(isset($getfilter3result)){
$filter3= array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => 'filter3',
        'operator' => 'IN',
    );
array_merge($mergedarrays, $filter3);
}
$taxquery= array(
    'relation' => 'AND',
    echo $mergedarrays; //obviously this is not the right way to do this
);

I tried this way, but its showing none of the results instead of all of them.

$termsin= [];
if(isset($filter1)){
  $filter1= filtered1;
  $termsin=$array_push($termsin, $filter1);
}
if(isset($filter2)){
  $filter2= filtered2;
  $termsin=$array_push($termsin, $filter2);
}
if(isset($filter3)){
  $filter3= filtered3;
  $termsin=$array_push($termsin, $filter2);
}

$taxquery= array(
        'taxonomy' => 'version-filter',
        'field'    => 'slug',
        'terms'    => $termsin,
        'operator' => 'IN',
);

How can I get it to work properly? Am I missing some basic function that might come in handy right now? Looks like you all are showing me how to use basic functions, thanks.

I call it my. I use $args array.

'tax_query' => $taxquery,

Leave a Comment