<?php
/** Some types of product attributes for WooCommerce (those that are not taxonomies or used for variations)
** are saved only in the '_product_attributes' custom field, as an array.
** To index this custom field (which does not appear in the facet's Data source setting dropdown), select 'Post Type' as the facet's Data source
** and use below 'facetwp_index_row' hook to find and index the correct attributes.
**/
add_filter( 'facetwp_index_row', function( $params, $class ) {
if ( 'attributes' == $params['facet_name'] ) { //change 'attributes' to name of your facet
$product_id = $params['post_id'];
$attributes = get_post_meta( $product_id, '_product_attributes', true);
$values = maybe_unserialize( $attributes);
if ( is_array( $values ) && ! empty( $values ) ) {
foreach ( $values as $key => $value ) {
if ( 'test-attr' == $key ) { // Name of attribute, lowercase, "-" in place of spaces, "Test Attr" = 'test-attr'
$attrs = explode( '|', $value['value'] );
foreach ( $attrs as $attr ) {
$params['facet_value'] = trim( $attr );
$params['facet_display_value'] = $params['facet_value'];
$class->insert( $params ); // insert new value to the database
}
}
}
}
$params['facet_value'] = ''; // skip original row
}
return $params;
}, 10, 2 );