Created
December 28, 2023 08:00
-
-
Save sachyya/7a3fad77fccde697262de949a5ae5423 to your computer and use it in GitHub Desktop.
Indexing Product Variations by Attribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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