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, it doesn’t matter whether you return that or not. So, simply end your filter with

return array($your_processed_hit_array);

For more information, see more examples in user manual.

  • rvencu

    I tried, it does not work for me, no idea why.

  • Bryan Monroe

    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.

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

  • Drew

    I’d love to see a code example of how to use this. Mikko do you have something easy you can show us? Thanks!

  • Max Hodges

    Maybe useful: here’s my relevanssi_hits_filter

    can sort (asc and desc) by
    -a meta_value (called ‘_likes’ in my case)
    -wordpress total_comments count

  • Pingback: Get relevant search results in WordPress using Relevanssi and Ajax | Joe Buckle's Blog()

  • Rustam Uteev

    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!