Skip to content

Instantly share code, notes, and snippets.

@felipeelia
Last active March 18, 2021 17:50
Show Gist options
  • Save felipeelia/aa73cdfb48e7ce578d4f12a6c0cfca90 to your computer and use it in GitHub Desktop.
Save felipeelia/aa73cdfb48e7ce578d4f12a6c0cfca90 to your computer and use it in GitHub Desktop.
ElasticPress - Index product variation titles into the parent product
<?php
// Create a new field with product variation titles.
add_filter(
'ep_prepare_meta_data',
function( $post_meta, $post ) {
if ( 'product' !== get_post_type( $post ) ) {
return $post_meta;
}
$product = wc_get_product( $post );
$product_variations = $product->get_children();
if ( $product_variations ) {
$variation_titles = [];
foreach ( $product_variations as $product_var_id ) {
$variation_titles[] = get_the_title( $product_var_id );
}
$post_meta['product_variation_titles'] = wp_json_encode( $variation_titles );
}
return $post_meta;
},
10,
2
);
// Add the new field to the weighting dashboard.
add_filter(
'ep_weighting_fields_for_post_type',
function( $fields, $post_type ) {
if ( 'product' === $post_type ) {
if ( empty( $fields['meta'] ) ) {
$fields['meta'] = array(
'label' => 'Custom Fields',
'children' => array(),
);
}
$key = 'meta.product_variation_titles.value';
$fields['meta']['children'][ $key ] = array(
'key' => $key,
'label' => 'Product Variation Titles',
);
}
return $fields;
},
10,
2
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment