Combine facet choices in a facet with a global attribute as data source

<?php

// Combines specific choices in a facet that has its data source set to a 'farbe' (color) global product attribute.
// The value is combined with another global attribute 'holzart' (wood type) for certain holzart-farbe combinations.
// E.g. products with the global attributes 'Eiche' and 'Farblos', and 'Buche' and 'Farblos', need to be indexed as 'NATUR'.
// All other combinations need to be indexed with the holzart and farbe values, e.g. 'Esche Farblos'.
// Note: this works for simple products, not variation products.

add_filter('facetwp_index_row', function ($params, $class) {

  if ('farbigkeit' == $params['facet_name']) {

    $product_id = $params['post_id'];
    $pa_farbe_name = $params['facet_display_value']; // The facet has data source 'pa_farbe' already, so it alrady has the display value

    // Get the global attribute term name  
    $product = wc_get_product( $product_id );
    $product_attributes = $product->get_attributes();
    $pa_holzart_id = $product_attributes['pa_holzart']['options']['0']; // returns the ID of the term
    $pa_holzart_name = get_term($pa_holzart_id)->name; // returns the term name

    // Custom logic for combining "Holzart" and "Farbe" into "NATUR"
    if ( ('Eiche' == $pa_holzart_name && 'Farblos' == $pa_farbe_name) || ('Buche' == $pa_holzart_name && 'Farblos' == $pa_farbe_name) ) {
      $combined_display_value = 'NATUR';
      $combined_value = 'natur';
    } else {
      $combined_display_value = $pa_holzart_name . ' ' . $pa_farbe_name; // Set the display value as e.g. 'Esche Farblos'
      $combined_value = str_replace(' ', '_', strtolower($combined_display_value)); // Set the technical value as e.g. esche_farblos (lowercase and spaces replaced with underscores)
    }

    $params['facet_display_value'] = $combined_display_value;
    $params['facet_value'] = $combined_value;

  }
  return $params;
}, 10, 2);