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.)

2 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

Leave a Reply

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