Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Created April 1, 2020 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/29195c941449946580dd2804818caf1c to your computer and use it in GitHub Desktop.
Save jchristopher/29195c941449946580dd2804818caf1c to your computer and use it in GitHub Desktop.
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