How to search Products by variation SKUs?

Indexing variation SKUs to the parent product

For this to work, make sure you have configured and using the index table engine - as well as the search in SKUs search is enabled.

By default, when the _sku field is selected, the plugin will index the product SKUs as well as the variation SKUs - but all separately. To associate the variation SKUs with the parent product as well, use the code below.

After adding the custom code, make sure to re-create the search index.

What is this, and where do I put this custom code?

add_filter( 'asp_post_custom_field_before_tokenize', 'asp_tokenize_sku_variation', 10, 3 );
function asp_tokenize_sku_variation($values, $post, $field) {
	if ( $post->post_type == 'product' && $field == '_sku' ) {
		$args = array(
			'post_type'     => 'product_variation',
			'post_status'   => array( 'private', 'publish' ),
			'posts_per_page'  => -1,
			'fields'          => 'ids',
			'post_parent'   => $post->ID // get parent post-ID
		);
		$variations = get_posts( $args );
		$skus = array();
		foreach ( $variations as $variation ) {
			$sku = get_post_meta($variation, '_sku', true);
			if ( !empty($sku) ) {
				$skus[] = $sku;
			}
		}
		if ( count($skus) > 0 ) {
			$values = array_merge($values, $skus);
		}
	}

	return $values;
}

After adding the custom code, make sure to re-create the search index.

Last updated

Copyright Ernest Marcinko