Created
April 1, 2020 12:44
-
-
Save jchristopher/29195c941449946580dd2804818caf1c to your computer and use it in GitHub Desktop.
Index WooCommerce Product Variation SKUs in SearchWP.
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 | |
// @link https://searchwp.com/documentation/knowledge-base/woocommerce-product-variation-skus/ | |
// Index WooCommerce Product Variation SKUs alongside the parent Product. | |
add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) { | |
$entry = $entry->native(); | |
if ( ! $entry instanceof \WP_Post || 'product' !== get_post_type( $entry ) ) { | |
return $data; | |
} | |
// The 'extra' meta_key we'll use to store these SKUs. | |
$product_variation_key = 'swp_wc_product_variation_sku'; | |
// Retrieve all Product Variations. | |
$product_variations = get_posts( [ | |
'post_type' => 'product_variation', | |
'nopaging' => true, | |
'fields' => 'ids', | |
'post_parent' => $entry->ID, | |
] ); | |
if ( empty( $product_variations ) ) { | |
return $data; | |
} | |
$product_variation_skus = []; | |
foreach ( $product_variations as $product_variation ) { | |
$product_variation_skus[] = get_post_meta( $product_variation, '_sku', true ); | |
} | |
$data['meta'][ $product_variation_key ] = new \SearchWP\Tokens( array_filter( $product_variation_skus ) ); | |
return $data; | |
}, 20, 2 ); | |
// Add 'extra' meta_key as available option. | |
add_filter( 'searchwp\source\attribute\options', function( $keys, $args ) { | |
if ( $args['attribute'] !== 'meta' ) { | |
return $keys; | |
} | |
// This key is the same as the one used to store the Product Variation SKUs | |
// in the searchwp\entry\data hook above, they must be the same. | |
$product_variation_key = 'swp_wc_product_variation_sku'; | |
// Add "Product Variation SKUs" Option if it does not exist already. | |
if ( ! in_array( | |
$product_variation_key, | |
array_map( function( $option ) { return $option->get_value(); }, $keys ) | |
) ) { | |
$keys[] = new \SearchWP\Option( $product_variation_key, 'Product Variation SKUs' ); | |
} | |
return $keys; | |
}, 20, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment