Let’s see if I can understand. Tell me if I go wrong at some point:
1. Usually WooCommerce has the SKU in the custom field _sku. For some reason, on your site, the custom field is named sku.
2. You’ve set Relevanssi to index the custom field sku and have rebuilt the index after that.
3. The search is still not finding posts when you search for the SKU.
Is that right?
The search finds products, but this is a list and the desired product may be at the end of the list. It is necessary that there is a specific match.
Try adding this to your theme functions.php:
add_filter( 'relevanssi_results', 'rlv_exact_boost' );
function rlv_exact_boost( $results ) {
$query = strtolower( get_search_query() );
foreach ( $results as $post_id => $weight ) {
$post = relevanssi_get_post( $post_id );
if ( get_post_meta( $post_id, 'sku', true ) === $query ) {
$results[ $post_id ] = $weight * 1000;
}
}
return $results;
}
This should lift exact matches in the sku custom field to the top of the results.
Excellent! It works. Is it possible to hide other products if found by SKU?
Yes:
add_filter( 'relevanssi_results', 'rlv_exact_boost' );
function rlv_exact_boost( $results ) {
$query = strtolower( get_search_query() );
$sku_matches = array();
foreach ( $results as $post_id => $weight ) {
if ( get_post_meta( $post_id, 'sku', true ) === $query ) {
$sku_matches[ $post_id ] = $weight;
}
}
if ( ! empty( $sku_matches ) ) {
return $sku_matches;
}
return $results;
}
This version will only return the exact SKU matches, if any are found, and the rest of the results if not.