Skip to main contentSkip to footer

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

Your account

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

Search

Popular Resources

10Web Photo Gallery
The Photo Gallery plugin from 10Web uses a shortcode to add photo galleries to posts and pages. By default, Relevanssi…
WP e-Commerce
WP e-Commerce is a popular shopping cart plugin for WordPress. This code by Alexander Gieg, added to functions.php for example,…

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