I'm building a filter system with checkboxes for a custom post type.
I think the Wordpress query expects that same types of taxonomies are in the same array.
The code below doesn't display any 'merk' (brand). If I just select one brand it works well, selecting multiple boxes with different taxonomies also works well. I currently use a for loop to walk trough all the checkboxes and add to the array when it's checked.
$array = [
'relation' => 'AND',
[
'taxonomy' => 'merk',
'field' => 'slug',
'terms' => ['coral']
],
[
'taxonomy' => 'merk',
'field' => 'slug',
'terms' => ['deluxe']
]
];
Is there a way to programmatically merge them when the taxonomy is the same so that it would result in this:
[
'relation' => 'AND',
[
'taxonomy' => 'merk',
'field' => 'slug',
'terms' => ['coral', 'deluxe']
]
];
While looping, modify your array by reference (instead of iterating a copy of the array). If an item has a
taxonomyand afieldelement, then it qualifies for consolidation. On the first encounter, declare thetermsarray as a reference. If the sametaxonomyandfieldcombination is encountered again, push the one or more elements from thetermssubarray into the reference.Code: (Demo)
Output: