• Resolved remy00

    (@remy00)


    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.

    The one thing: A multiple word search term is separated (which is generally good), but through the filter of “relevanssi_match” I only get the word which applied to the result – so I cannot check if the complete term matches exactly the title. The other thing: How can I remove the other results, when there is an exact match? There is a filter “relevanssi_results”, but there I don’t know if and which post is an exact match. On top there is the challenge that short words like “a” are removed from the search term…

    Any hint to solve this problem would be great ?? Thank you!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Mikko Saari

    (@msaari)

    Here’s how you can do this:

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

    This filter matches the post titles to the original search query (from get_search_query()) and if there’s a match, only exact match results are returned.

    Thread Starter remy00

    (@remy00)

    Thanks for the fast answer, this works like a charm!

    I had an issue using “get_search_query()” , as I use Relevanssi in combination with Ajax Load More. It seems that these ajax calls are no real search queries through wp, so I had to use:

    $search_query = strtolower($_GET['search']);

    Maybe this helps other people. Also $_GET should maybe be filtered for security reasons.

    Plugin Author Mikko Saari

    (@msaari)

    Correct, AJAX queries don’t appear in get_search_query(). It’s safe to use the $_GET parameters like this; you’re just comparing it with the post title. Can’t attack that way.

    Thread Starter remy00

    (@remy00)

    Thanks again for your clarification!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Exact match with multiple word search’ is closed to new replies.