Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active January 18, 2022 13:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/0cad8418fd9477c57b53 to your computer and use it in GitHub Desktop.
Save jchristopher/0cad8418fd9477c57b53 to your computer and use it in GitHub Desktop.
Index WooCommerce product variation SKUs with the parent product
<?php
// index WooCommerce product_variation SKUs with the parent post
function my_searchwp_index_woocommerce_variation_skus( $extra_meta, $post_being_indexed ) {
// we only care about WooCommerce Products
if ( 'product' !== get_post_type( $post_being_indexed ) ) {
return $extra_meta;
}
// retrieve all the product variations
$args = array(
'post_type' => 'product_variation',
'posts_per_page' => -1,
'fields' => 'ids',
'post_parent' => $post_being_indexed->ID,
);
$product_variations = get_posts( $args );
if ( ! empty( $product_variations ) ) {
// store all SKUs as a Custom Field with a key of 'my_product_variation_skus'
$extra_meta['my_product_variation_skus'] = array();
// loop through all product variations, grab and store the SKU
foreach ( $product_variations as $product_variation ) {
$extra_meta['my_product_variation_skus'][] = get_post_meta( absint( $product_variation ), '_sku', true );
}
}
return $extra_meta;
}
add_filter( 'searchwp_extra_metadata', 'my_searchwp_index_woocommerce_variation_skus', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment