• Resolved Andrea

    (@licoreo)


    Hello,
    i have a problem with this plugin
    if i search a sku without slash and space is everything good,
    but if i search a sku with space and slash (for example TER 100/ARAN ) i have many results

    i read other similar task and the common suggestion is save sku without space, the problem is that if user search TER100/ARAN not found TER 100/ARAN

    i think about a filter that if the search string are exctly a sku report only the relative product
    it is possible?

    thank you

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Mikko Saari

    (@msaari)

    It’s possible, but slightly complicated.

    Relevanssi searches “TER 100/ARAN” as “TER 100 ARAN”, so since you likely have OR operator enabled, it’ll return all posts that have either “TER”, “100” or “ARAN”.

    A good first step would be to remove the slash:

    add_filter( 'relevanssi_punctuation_filter', 'rlv_remove_slash' );
    function rlv_remove_slash( $replacements ) {
        $replacements['/'] = '';
        return $replacements;
    }

    If you add this to the theme functions.php and rebuild the index, now the slashes will be removed and the search becomes “TER 100ARAN”. That’s probably more precise, but if you have lots of TER products, it may still return too many results.

    Spaces are the tricky part, since removing them from all places is not possible and removing from only certain places is hard because then the search terms don’t match.

    If the fix above isn’t good enough, then something like this might work:

    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 = '_sku' AND meta_value = %s",
    			$hits[1]
    		)
    	);
        if ( ! $post_ids ) {
            return $hits;
        }
    	$hits[0] = array_filter(
    		$hits[0],
    		function( $hit ) use ( $post_ids ) {
    			return in_array( $hit->ID, $post_ids, false );
    		}
    	);
    	return $hits;
    }

    Add this to the theme functions.php, and whenever a search matches a SKU exactly, only the products with that SKU will be returned.

    Thread Starter Andrea

    (@licoreo)

    the last code is perfect!
    thank you so much!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘search bad formed sku’ is closed to new replies.