Posted on

Return only exact matches for SKU searches

This little filter function works on relevanssi_hits_filter. When a search query is made that matches a SKU (or any other custom field, but SKUs are the most likely scenario here), only results that match the SKU will be returned.

In order for this to work, Relevanssi must be set to index the _sku custom field (because otherwise SKU search will not find anything) and the search query must match the SKU exactly.

Add this code to your theme functions.php file:

add_filter( 'relevanssi_hits_filter', 'rlv_sku_exact_match' );
function rlv_sku_exact_match( $hits ) {
    global $wpdb;
    $post_ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'status' AND meta_value = %s",
			$hits[1]
		)
	);
    if ( ! $post_ids ) {
		// No matches found, don't touch the results.
        return $hits;
    }
	// Return only results with ID numbers that are in $post_ids.
	$hits[0] = array_filter(
		$hits[0],
		function( $hit ) use ( $post_ids ) {
			return in_array( $hit->ID, $post_ids, false );
		}
	);
	return $hits;
}

Now any searches that match a SKU in the database should only return the product matching the SKU.

One comment Return only exact matches for SKU searches

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.