0

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']
    ]
];
mickmackusa
  • 43,625
  • 12
  • 83
  • 136

1 Answers1

0

While looping, modify your array by reference (instead of iterating a copy of the array). If an item has a taxonomy and a field element, then it qualifies for consolidation. On the first encounter, declare the terms array as a reference. If the same taxonomy and field combination is encountered again, push the one or more elements from the terms subarray into the reference.

Code: (Demo)

$array = [ 
    'relation' => 'AND',
    [
        'taxonomy' => 'merk',
        'field' => 'slug', 
        'terms' => ['coral']
    ],
    [
        'taxonomy' => 'foo',
        'field' => 'bar', 
        'terms' => ['stackoverflow']
    ],
    [
        'taxonomy' => 'merk',
        'field' => 'slug', 
        'terms' => ['deluxe', 'ultra']
    ]
];

foreach ($array as $key => &$item) {
    if (is_array($item) && isset($item['taxonomy'], $item['field'])) {
        $id = $item['taxonomy'] . '_' . $item['field'];
        if (!isset($ref[$id])) {
            $ref[$id] = &$item['terms'];
        } else {
            array_push($ref[$id], ...$item['terms']);
            unset($array[$key]);
        }
    }
}
var_export($array);

Output:

array (
  'relation' => 'AND',
  0 => 
  array (
    'taxonomy' => 'merk',
    'field' => 'slug',
    'terms' => 
    array (
      0 => 'coral',
      1 => 'deluxe',
      2 => 'ultra',
    ),
  ),
  1 => 
  array (
    'taxonomy' => 'foo',
    'field' => 'bar',
    'terms' => 
    array (
      0 => 'stackoverflow',
    ),
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136