Skip to content

Instantly share code, notes, and snippets.

@sachyya
Created December 28, 2023 08:00
Show Gist options
  • Save sachyya/7a3fad77fccde697262de949a5ae5423 to your computer and use it in GitHub Desktop.
Save sachyya/7a3fad77fccde697262de949a5ae5423 to your computer and use it in GitHub Desktop.
Indexing Product Variations by Attribute
<?php
// Add sex variation to the schema
add_filter( 'cm_tsfwc_product_fields', 'your_slug_add_stock_status_to_schema' );
function your_slug_add_stock_status_to_schema( $product_fields ) {
$product_fields[] = [ 'name' => 'sex_variation', 'type' => 'string[]', 'facet' => true ];
return $product_fields;
}
// Data entry for sex_variation for indexing
add_filter( 'cm_tsfwc_data_before_entry', 'your_slug_add_data_before_entry', 10, 4 );
function your_slug_add_data_before_entry( $formatted_data, $raw_data, $object_id, $schema_name ) {
if( $schema_name === 'product' ) { // only add data if the schema is product
$sex_variation_arr = [];
// Check if the product is variable (has variations)
if ($raw_data->is_type('variable')) {
// Get the product variations
$variations = $raw_data->get_variation_attributes();
foreach ( $variations['pa_sex'] as $sex_variation ) {
$sex_variation_arr[] = $sex_variation;
}
}
$formatted_data['sex_variation'] = $sex_variation_arr;
}
return $formatted_data;
}
// Display Sex filter on front end
add_action( 'cm_tsfwc_custom_attributes', 'sex_variation' );
function sex_variation() {
echo '<div
data-facet_name="sex_variation"
data-attr_facet_name="sex_variation"
data-title ="' . __( "Sex", 'storefront' ) . '"
data-attr_label ="' . __( "Sex", 'storefront' ) . '"
class="cm-tsfwc-shortcode-tags-attribute-filters"
data-filter_type="refinementList"
data-settings="' . _wp_specialchars( json_encode( [ "searchable" => false ] ), ENT_QUOTES, "UTF-8", true ) . '"
></div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment