Skip to main contentSkip to footer

In regular expressions, ^ can be used to match the beginning of the line and $ to match the end of the line. For example, ^ban will match banana, but not urban, while ban$ matches urban, but not banana. These are called anchoring operators.

By default, Relevanssi matches either beginning or the end of the word, but not in the middle – ban will match banana or urban, but not abandon. If you want more control over this in the search, you can add support for the ^ and $ operators in Relevanssi using the relevanssi_fuzzy_query filter hook.

Add this to your site:

add_filter( 'relevanssi_fuzzy_query', 'rlv_edge_operators' );
function rlv_edge_operators( $query ) {
    if ( isset( $_REQUEST['s'] ) && '^' === substr( $_REQUEST['s'], 0, 1 ) ) {
        return "(relevanssi.term LIKE '#term#%')";
    }
    if ( isset( $_REQUEST['s'] ) && '$' === substr( $_REQUEST['s'], -1 ) ) {
        return "(relevanssi.term_reverse LIKE CONCAT(REVERSE('#term#'), '%'))";
    }
    return $query;
}

This is a very simple version that works best with single-word searches: it always looks at the first and last character of the whole search query. So, if you search for ^ban foo, it’s the same as searching for ^ban ^foo and searching for ban ^foo is the same as searching for ban foo.

Creating a smarter version that analyzes the search query and offers support for using different operators for individual words in the query is left as an exercise for the reader.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Polylang: Bilingual search
By default, Relevanssi indexes the different language versions of the posts separately. If your site is in French and English,…
Yoast Local SEO
Yoast Local SEO plugin breaks Relevanssi search. It enhances the search by adding meta queries. Unfortunately they don’t work with…
PostX Pro
If you use PostX Pro to build a search results template using their Post Grid block, you’ll notice that the…

Related Posts:

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed