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

SearchWP Live Ajax Search

…One example is searching for attachments. By default, SearchWP Live Ajax Search doesn’t include any attachments in the search results. The post type is not a problem, but the post status is: SearchWP Live Ajax Search includes only posts with the post status publish, while attachments have a status of…Relevanssi doesn’t ship with a live search or autocomplete feature that would display results as the user types the search terms. There are many other plugins that provide this functionality, but few of these plugins work with Relevanssi. SearchWP Live Ajax Search is the best one that does. It’s very……to include private posts for the users who are allowed to see them. Just removing the post_status parameter will include drafts in the results. Normally drafts shouldn’t appear in searches, but since the SearchWP Live Ajax Search is an AJAX search, it is done in admin context, where drafts are…

Gmedia photo gallery tags
Gmedia photo gallery gives a false impression of working with Relevanssi, as you can see the gmedia_tag taxonomy appear in…

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