Posted on

Only return exact title matches if possible

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;
} );

Leave a Reply