If you want to fine-tune the post weights, version 1.4.5 introduces a new hook for that. The relevanssi_match hook lets you modify the matches found for queries. It passes a match object, which has the post id ($match->doc), number of hits found in different parts of the post and the weight assigned to the post ($match->weight).
From version 1.7.4 onwards, there’s another parameter included. That parameter contains the IDF value used for calculating the weight.
Here’s how the weight is calculated:
$match->tf = $match->title * $title_boost + $match->content + $match->comment * $comment_boost + $match->tag * $tag_boost + $match->link * $link_boost + $match->author + $match->category + $match->excerpt + $match->taxonomy + $match->customfield; $match->weight = $match->tf * $idf; |
Where $idf is the inverse document frequency, aka the rarity of the term in question. The bigger the weight, the higher the document will appear on the search results list. Weights are calculated for each term in the search query and multiplied to get the final weight for the document.
So, now, if you want to say adjust the weights by freshness, you could fetch the post date based on post_id and multiply the $match->weight with some boost factor if the publication date falls within some range (say within the last week) and with another boost factor if it falls outside that range. Want to boost the weight if a certain custom field is present? Easy!
This filter will give you lots of tools to adjust and fine-tune the weights given to documents.
Date-based weight
Here’s an example function that will give double weight to posts published within one week and half weight to posts older than that.
add_filter('relevanssi_match', 'date_weights'); function date_weights($match) { $post_date = strtotime(get_the_time("Y-m-d", $match->doc)); if (time() - $post_date < 60*60*24*7) { $match->weight = $match->weight * 2; } else { $match->weight = $match->weight / 2; } return $match; } |
Custom field -based weight
This function will double the weight of posts with the custom field “featured” set to 1.
add_filter('relevanssi_match', 'custom_field_weights'); function custom_field_weights($match) { $featured = get_post_meta($match->doc, 'featured', true); if ('1' == $featured) { $match->weight = $match->weight * 2; } else { $match->weight = $match->weight / 2; } return $match; } |