How to search for WooCommerce Global Attributes
Although ElasticPress indexes your WooCommerce global attributes by default, they are not displayed in the Search Fields & Weighting dashboard. If you want to make your user able to search for “blue” and find all products with that “Color” attribute, add the following snippet to your codebase and enable the attribute in your Search Fields & Weighting dashboard.
PHP
<?php
/**
* Add all WooCommerce Global Attributes to the ElasticPress Weighting Dashboard.
*
* @param array $fields Current weighting fields.
* @param string $post_type Current post type.
* @return array New fields.
*/
function ep_custom_add_all_wc_attributes( $fields, $post_type ) {
if ( 'product' !== $post_type ) {
return $fields;
}
$attribute_names = wc_get_attribute_taxonomy_names();
foreach ( $attribute_names as $name ) {
if ( ! taxonomy_exists( $name ) ) {
continue;
}
$attribute_field = "terms.{$name}.name";
if ( isset( $fields['taxonomies']['children'][ $attribute_field ] ) ) {
continue;
}
$taxonomy = get_taxonomy( $name );
$fields['taxonomies']['children'][ $attribute_field ] = [
'key' => $attribute_field,
'label' => $taxonomy->label,
];
}
return $fields;
}
add_filter(
'ep_weighting_fields_for_post_type',
'ep_custom_add_all_wc_attributes',
10,
2
);