Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Index WooCommerce Product Variation SKUs in SearchWP.
<?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
You can’t perform that action at this time.