Posted on

Adding extra boost for exact title matches

Every now and then somebody wants to see exact title matches higher in the results. Usually the best way to go about with this is to simply increase the title weight, maybe switch the default operator to AND and let the Relevanssi algorithm lift the best results on top.

If that is not enough, you can use this code to give a boost for exact matches in titles and post content:

add_filter('relevanssi_results', 'rlv_exact_boost');
function rlv_exact_boost($results) {
	$query = strtolower(get_search_query());
	foreach ($results as $post_id => $weight) {
		$post = relevanssi_get_post($post_id);
 
                // Boost exact title matches
		if (stristr($post->post_title, $query) != false) $results[$post_id] = $weight * 100;
 
                // Boost exact matches in post content
		if (stristr($post->post_content, $query) != false) $results[$post_id] = $weight * 100;
	}
	return $results;
}

This code, placed in for example theme functions.php, gives a solid boost for posts with titles and content that match the search query.

(If you want to be 100% sure, you can write a relevanssi_hits_filter function that moves the exact matches on top of the results.)

6 comments Adding extra boost for exact title matches

  1. Hi mr. Saari,
    I’m using your plugin on a woocommerce install. I’m using it only to products. How to modify this code to give extra weight to product title instead of post title?
    thank you

  2. Hi Mikko,
    I got the most matched on top of result. If my search is “iphone X”, so results are:

    Iphone x Blue
    Iphone x Black
    Iphone 7
    Iphone 6

    How to only display match 100% results? (Remove Iphone 7 and Iphone 6 in result)?

    1. Will, try adding this to your theme functions.php:

      <pre lang="php">add_filter('relevanssi_results', 'rlv_exact_boost');
      function rlv_exact_boost($results) {
      	$query = strtolower(get_search_query());
      	foreach ($results as $post_id => $weight) {
      		$post = relevanssi_get_post($post_id);
      		if (stristr($post->post_title, $query) === false) $results[$post_id] = $weight * 0;
      	}
      	return $results;
      }

      This should remove all posts where the serach query isn’t found in the title (that may be too harsh, but it’s a start).

  3. Hi Mikko,
    How can I show all results that contain a partial word, ex:
    I have some products 6MB200 and 6MB200-4 when Im search “6MB200” only show one result on the query “6MB200-4”.

Leave a Reply

Your email address will not be published. Required fields are marked *