Skip to main contentSkip to footer

We have posts with titles like “A perfect match”. If a user searches for this exact title, only this post should show up in the results. Otherwise, the search should run as default.

There are several approaches to this, but the best is relevanssi_hits_filter. This function goes through all the posts, checks if the post title matches the search query exactly (but case-insensitively), and if there’s an exact match, Relevanssi returns only the exact match. Otherwise, Relevanssi returns all found posts.

Add this to your site:

add_filter( 'relevanssi_hits_filter', function( $hits ) {
    $exact_title  = array();
    $the_rest     = array();
    $search_query = strtolower( get_search_query() );
    foreach ( $hits[0] as $hit ) {
        if ( $search_query === strtolower( $hit->post_title ) ) {
            $exact_title[] = $hit;
        } else {
            $the_rest[] = $hit;
        }
    }
    if ( count ( $exact_title ) > 0 ) {
        $hits[0] = $exact_title;
    } else {
        $hits[0] = $the_rest;
    }
    return $hits;
} );

Your account

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

Search

Popular Resources

Flatsome
Posts and pages on the product search results The Flatsome theme, when combined with WooCommerce, has a product search results…

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