Posted on

Different fuzzy search setting on different searches

On one of our sites we have 2 search boxes, one where you can do a normal search and the other where you can search for employees or departments. The employees/department search is done by using the relevanssi_do_query() function.

Can we use fuzzy matching on the normal search and disable it on the employees/department search?

Yes, you can, but it takes some hacking. Since Relevanssi has just one setting for the fuzzy search, you need to change it on the fly for one of the searches. It’s probably easier to do with the relevanssi_do_query() search.

Relevanssi reads the fuzzy search setting from the relevanssi_fuzzy option. WordPress provides you with pre_option_relevanssi_fuzzy filter you can use to change the value. The values are “always” and “sometimes”, and everything else counts as none. So, set the setting to always from Relevanssi settings, and then add a filter function that sets the value to, for example, “none” when you’re doing an employee/department search.

For example, you can set a global variable before the relevanssi_do_query(), like this:

global $relevanssi_disable_fuzzy;
$relevanssi_disable_fuzzy = true;
relevanssi_do_query( $args );

Then use that global variable as a trigger:

add_filter( 'pre_option_relevanssi_fuzzy', 'rlv_disable_fuzzy' );
function rlv_disable_fuzzy( $value ) {
    global $relevanssi_disable_fuzzy;
    if ( $relevanssi_disable_fuzzy ) $value = "none";
    return $value;
}

The pre_option_ filter hooks are, in general, a mighty powerful tool to know.