Posted on

Using the relevanssi_hits_filter hook

A very useful hook relevanssi_hits_filter, which lets you modify the hits directly. The filter passes an array, where index 0 gives the list of hits in the form of an array of post objects and index 1 has the search query as a string, in case you need that information for something.

The filter is very nice, if you want to adjust the search results some how. You can add posts to the results, make sure some posts float on top, remove certain posts… The WPML support Relevanssi has, for example, is based on this filter: results that are not in the correct language are filtered away at this point.

The filter expects you to return an array containing the array of post objects in index 0. The search query is just for information, but if there are many filters on the relevanssi_hits_filter hook, some later function may expect it to be there. So, in order to avoid problems, it’s best to include the query string in the returned array, like this (assuming the function parameter array is called $hits):

$hits[0] = $your_processed_hits_array;
return $hits;

For more information, see more examples in user manual.

10 comments Using the relevanssi_hits_filter hook

  1. Do you have a suggestion for how to modify the filter to float results to the top by page type? I’ve built out all of the top pages on my site as tag pages and want those pages to appear at the top of search when there are any hits for those tags.

    1. Is there anything in the posts that you can use to recognize those tag pages? What does their post_type say? You can easily filter by any feature that’s present in the $post object.

  2. Hi Mikko!

    First of all thank you for the great plugin and your support. I have trouble in using relevanssi_hits_filter hook. It just doesn’t fire. I’d like to use it in functions.php. I also tried to use it in search.php but it doesn’t work there as well.

    Can you help to identify the cause of the problem?

    Thank you in advance!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.