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

Restrict search by author from the search query

…small lesson in the power of caching here as well. Notice the $author_list is taken from a transient, and only if it doesn’t exist, it’s generated with wp_list_authors(). The transient is stored for a week – because in most cases the list of authors is fairly stable – so the……of how you can optimize and cache using the transients. If you have a very stable list of authors, it’s not a bad idea to remove the whole affair with wp_list_authors() and the transients, and instead just list all the authors you want to include directly as the $authors array….…Your mileage may vary, depending on the number of authors on your site for example, but it’s clear that is potentially a very expensive function. Since it produces output that’s stable and easy to cache, it’s a very good example of how you can optimize and cache using the transients….

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