Posted on

Indexing product variation SKUs for main product

Relevanssi can index product and product variation SKUs for WooCommerce products: just add _sku to list of custom fields to index. However, if you want to find the main product when searching for the product variation SKU, you need some extra code. Just add this function to the theme functions.php and rebuild the index:

add_filter('relevanssi_content_to_index', 'rlv_index_variation_skus', 10, 2);
function rlv_index_variation_skus($content, $post) {
	if ($post->post_type == "product") {
		$args = array('post_parent' => $post->ID, 'post_type' => 'product_variation', 'posts_per_page' => -1);
		$variations = get_posts($args);
		if (!empty($variations)) {
			foreach ($variations as $variation) {
				$sku = get_post_meta($variation->ID, '_sku', true);
				$content .= " $sku";
			}
		}
	}
 
	return $content;
}

This will index the product variation SKUs for the main product, and you will be able to find the main product when searching for the variation SKU.

Leave a Reply

Your email address will not be published. Required fields are marked *