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.
1
add_filter( 'asp_post_custom_field_before_tokenize', 'asp_tokenize_sku_variation', 10, 3 );
2
function asp_tokenize_sku_variation($values, $post, $field) {
3
if ( $post->post_type == 'product' && $field == '_sku' ) {
4
$args = array(
5
'post_type' => 'product_variation',
6
'post_status' => array( 'private', 'publish' ),
7
'posts_per_page' => -1,
8
'fields' => 'ids',
9
'post_parent' => $post->ID // get parent post-ID
10
);
11
$variations = get_posts( $args );
12
$skus = array();
13
foreach ( $variations as $variation ) {
14
$sku = get_post_meta($variation, '_sku', true);
15
if ( !empty($sku) ) {
16
$skus[] = $sku;
17
}
18
}
19
if ( count($skus) > 0 ) {
20
$values = array_merge($values, $skus);
21
}
22
}
23
24
return $values;
25
}
Copied!
After adding the custom code, make sure to re-create the search index.
Copy link