Filter hooks

Relevanssi has lots of filter hooks you can use to modify how the plugin behaves. Most of these are pretty advanced and an average user probably doesn’t have to worry about them, but if you’re going to do something more demanding, knowledge of these filters will help.

If you do something that would be made easier by a new filter, please let me know – I do like adding new filter hooks, as that is a very easy way to add flexibility to the plugin with little effort.

relevanssi_admin_search_ok (true, $query)
This filter can modify whether the default admin search query by WP is blocked or not.

relevanssi_bots_to_not_log ($bots_array)
This filter can be used to prevents bots from being logged in the user searches blog. This filter expects an array with key => value pairs where key is the name of the bot and value the user agent of the bot.

relevanssi_comment_content_to_index ($content, $comment_id)
Comment content is passed through this filter before indexing. You can use this filter to add any content to comments before they are indexed.

relevanssi_content_to_index (”, $post)
You can use this filter to add extra content to posts before Relevanssi indexes them. The additional content is then trimmed and a space is added between the old content and the added content.

relevanssi_default_meta_query_relation (‘OR’)
By default, Relevanssi assumes the meta query relation is OR. If you want to change the default relation to AND, you can use this filter hook to do so.

relevanssi_default_tax_query_relation (‘OR’)
By default, Relevanssi assumes the taxonomy query relation is OR. If you want to change the default relation to AND, you can use this filter hook to do so.

relevanssi_df_query_filter ($query)
Relevanssi calculates DF (document frequency) with a simple MySQL query. You can filter that query with this hook. Mostly useful if you modify the way fuzzy queries are done, in which case you’ll want to make the change to this query as well.

relevanssi_didyoumean_url ($url)
The URL produced by relevanssi_didyoumean() function is passed through this filter.

relevanssi_do_not_index (false, $post->ID)
If this filter returns true, Relevanssi will not index this post. You can use this filter to selectively prevent posts from being indexed.

relevanssi_ellipsis (“…”)
If you want to replace the … in the end and beginning of excerpts with something else, use this filter.

relevanssi_excerpt ($excerpt)
After the excerpt is generated, but before the ellipsis and highlighting is added, you can use this filter to modify the excerpt.

relevanssi_excerpt_content ($content, $post, $query)
When Relevanssi builds excerpts, the post content passes through this filter, after it goes through relevanssi_pre_excerpt_content and the_content. All these filters give you a chance to add more content to the post to work as a building block of excerpts. For example, if you want custom field content to appear in the excerpts in case the search term is found in a custom field, use this filter or relevanssi_pre_excerpt_content to simply concatenate the custom field content to the end of the post content – the excerpt building algorithm will find it there.

relevanssi_fuzzy_query (“(term LIKE ‘%#term#’ OR term LIKE ‘#term#%’) “)
This filter lets you modify the way Relevanssi runs the fuzzy queries. The main thing you can do here is to change this value to “(term LIKE ‘%#term#%’) ” to make it match search term completely inside words. By default the search term in fuzzy search must match either beginning or the end of a word. #term# will be replaced by the actual search term later.

relevanssi_get_words_query ($query) (Premium only)
Relevanssi Premium uses a “Did you mean” function that needs to know all the words in your database. This, however, can be problematic once your search index grows large enough. To fix that, you need to prune out the words that appear only once to make the amount of data smaller. This can be done using this hook. See “Did you mean” suggestions, the solution is in the end of the article.

relevanssi_hits_filter (array($hits, $query))
This is one of the most powerful filters in Relevanssi. It lets you modify the array $hits, which contains all the hits Relevanssi found. The hits are post objects, which makes manipulating them easy. At this point, you can reorder the search results at will, remove them, add new and so on. The parameter array also contains the search query, which Relevanssi doesn’t need back, it’s just there for reference in case you need it. Remember to return the array of posts like this: array($hits).

Relevanssi filter functions on this hook:
- relevanssi_wpml_filter() (default priority) adds WPML language support

relevanssi_index_comments_exclude (false, $post_id)
If this filter returns true, Relevanssi won’t index the comments for the $post_id mentioned in the second parameter.

relevanssi_index_content (true)
If this filter returns false, Relevanssi won’t index content of posts or pages.

relevanssi_index_custom_fields ($custom_fields)
The filter is given a list of custom fields before the custom fields are indexed. Feel free to manipulate the list as you wish. This can be useful for selecting the indexed custom fields with a regexp, for example.

relevanssi_index_taxonomies_args ($args)
When Relevanssi indexes taxonomy terms, it uses get_terms() to get the terms. By default Relevanssi uses the default arguments, but you can use this filter to modify that. One example case would be setting “hide_empty” to false to get the terms that are empty.

relevanssi_index_titles (true)
If this filter returns false, Relevanssi won’t index titles of posts or pages.

relevanssi_indexing_data ($data, $post)
Post data is passed through this filter before it is formed into MySQL value strings.

relevanssi_indexing_values ($data, $post)
Post data is passed through this filter before it is inserted into the database. In many cases, relevanssi_indexing_data is easier to use.

relevanssi_join ($data)
This can be used to JOIN tables to the Relevanssi search queries.

relevanssi_match ($match, $idf)
Another powerful filter. This lets you modify the $match objects, which are used to calculate the weight of the documents. The object has attributes which contain the number of hits in different categories. Post ID is $match->doc, term frequency (TF) is $match->tf and the total weight is in $match->weight. The filter is also passed $idf, which is the inverse document frequency (IDF). The weight is calculated as TF * IDF, which means you may need the IDF, if you wish to recalculate the weight for some reason.

relevanssi_modify_wp_query ($wp_query)
If you want to make some changes in the query before Relevanssi sees it, you can use this filter hook to modify the $wp_query variable before it is passed to Relevanssi. This is a good place, for example, to combine query variables. You can for example have one input field for positive search terms and another for negative search terms and then use this filter to combine them both into the ‘s’ query variable where Relevanssi will look for the search terms.

relevanssi_options_capability (‘manage_options’)
This filter can be changed to adjust the default capability required to see Relevanssi settings. The default value is ‘manage_options’.

relevanssi_post_ok ($post_ok, $post_ID)
Can this post be included in the search results? This is the hook you’ll use if you want to add support for a membership plugin, for example. Based on the post ID, your function needs to return true or false.

Relevanssi filter function on this hook:
- relevanssi_default_post_ok (priority: 9) contains the default logic. If you want to override this, either remove this function from the hook (and make sure you cover the cases for private posts or drafts, see the default function for more details) or run yours after this on a lower priority.

relevanssi_pre_excerpt_content ($post->post_content, $post, $query)
When Relevanssi builds excerpts, the post content passes first through this filter. Then it’s passed to the_content, then relevanssi_excerpt_content. All these filters give you a chance to add more content to the post to work as a building block of excerpts. For example, if you want custom field content to appear in the excerpts in case the search term is found in a custom field, use this filter or relevanssi_excerpt_content to simply concatenate the custom field content to the end of the post content – the excerpt building algorithm will find it there.

relevanssi_pre_indexing_query
This is an action hook that runs before the main indexing query. This is a fairly large query and can go over the MAX_JOIN_SIZE set on the server. If that is the case, you can use this action hook to run “SET OPTION SQL_BIG_SELECTS=1″ on the MySQL server to allow the large join.

relevanssi_query_filter ($query)
This is your final chance to modify the main Relevanssi query before it is run on the database. This is also useful for echoing out the query when doing debugging.

Relevanssi filter function on this hook:
- relevanssi_limit_filter() (default priority) adds the LIMIT parameter

relevanssi_post_content ($content, $post)
Post content is passed through this filter before indexing. You can use this filter to add any content you wish to posts before they are indexed.

relevanssi_post_content_before_tokenize ($content, $post)
Post content is passed through this filter just before it’s tokenized. You can use this filter to add content to posts before they are indexed.

relevanssi_premium_tokenizer ($token) (Premium only)
This hook is used to enable the stemmer in Premium. This filter sees every token (word) as it comes through the tokenizer, so you can use it for something else as well.

Relevanssi filter function on this hook:
- relevanssi_enable_stemmer (default priority, by default does nothing)

relevanssi_remove_punctuation
Relevanssi uses a hooked function to remove punctuation from search queries and documents. Some punctuation is replaced with spaces, some simply removed. If you’re interested in how this works, take a closer look at relevanssi_remove_punct() function in lib/common.php. If you want to change some of the behaviour, just unhook the default function and replace it with your own.

Relevanssi filter function on this hook:
relevanssi_remove_punct (default priority)

relevanssi_results ($results)
This filter lets you modify an array that contains (post_ID => weight) pairs. If unmodified, Relevanssi will fetch these posts and return them as the final search results (to another Relevanssi function, which will then take a slice of the array, as determined by how many posts are shown per page and which page of search results the user wants).

relevanssi_search_filters ($array)
This filter lets you manipulate search parameters before Relevanssi uses them. The array contains following keys: ‘q’, ‘cat’, ‘excat’, ‘tag’, ‘expost’, ‘post_type’, ‘taxonomy’, ‘taxonomy_term’, ‘operator’, ‘search_blogs’, ‘customfield_key’, ‘customfield_value’, ‘author’.

relevanssi_search_ok ($search_ok)
Relevanssi is activated always when posts are requested. Thus, Relevanssi needs to figure out if it’s an actual search, before taking action. If is_search() is true, it’s a search. If is_admin() is true, then Relevanssi will reconsider and so on. You can modify this behaviour with this hook, which is fired after Relevanssi has checked other cases. By returning a true here, you’ll force Relevanssi to become active. This is mostly useful when using Relevanssi without a search term where you’ll trigger Relevanssi based on active query variables.

relevanssi_show_matches ($matches)
If you use the “Show breakdown of search hits in excerpts” option, this filter lets you modify the breakdown before it is added to the excerpt.

relevanssi_stemmer ($token) (Premium only)
This hook is used to add a stemmer (or anything else that needs to process every search term and indexed word). Relevanssi Premium comes with a simple English stemmer (actually a suffix stripper), which you can enable:

add_function('relevanssi_stemmer', 'relevanssi_simple_english_stemmer');

relevanssi_term_add_data ($term, $taxonomy) (Premium only)
Use this filter to add extra data to taxonomy term objects before they are indexed.

relevanssi_tax_term_additional_content ($description, $term) (Premium only)
Taxonomy term description is passed through this filter before indexing, so you can add any content you wish to taxonomy term descriptions.

relevanssi_user_add_data ($user) (Premium only)
Use this filter to add extra data to user objects before they are indexed.

relevanssi_user_searches_capability (‘edit_pages’)
The capability level required to access the User Searches page.

relevanssi_valid_status ($statuses)
By default, Relevanssi indexes posts with a status of “publish”, “draft”, “private”, “pending” and “future” (not all of these posts are displayed to front end users). If you want to modify the statuses, you can do it with this filter.

relevanssi_where ($query_restrictions)
The way Relevanssi works is to search for the terms in the index, with a bunch of restrictions to restrict the search to certain post IDs (or to exclude particular post IDs). This filter gives you a chance to examine and modify those restrictions before they are used.

  • Mark Astengo

    Hello,
    Thank you for such a great plugin and your awesome support !

    I am using the networked version using a child theme from Twenty Eleven and WordPress 3.4.2 with Relevanssi Premium. Everything is working perfectly and I have implemented highlighting with css styling, “Did You Mean”, automatic indexing and stemming.

    The question I have is: how to I save the state of a not found search term?
    For example: I search for the term “spacewalk” and it is not found, so
    I do not want to retype, I just want to edit the term “spacewalk” to “space walk”

    I assume it is some sort of modification to the search.php file.

    Any help would be greatly appreciated.

    Mark

    • http://www.mikkosaari.fi/ Mikko Saari

      You can get the search term with get_search_query().

  • reddarmygeex

    hi, what if i’d like to make a multiple pulldown filter so i can choose objects first by tipology, then after that by designer and so on? is there any way to achieve that? :)

    • http://www.mikkosaari.fi/ Mikko Saari

      Just add several dropdowns, Relevanssi can handle multiple filters.

  • Jason Judge

    I am having some difficulty finding examples to back up this documentation. Are there any examples of filters being use that I just am not seeing?

    I have the premium version, and would like to be able to give users search options, so they can adjust the weight at search time. For example, one user may want to search everything. Another may want to limit their search to the “Artists” taxonomy (or make the weight of that taxonomy higher while lowering the weight of post titles an descriptions. Then a third user may want to search just track titles.

    Maybe adjusting the weight is not the right approach, and there is some other aspect of the filters that should be using?

    I have my Relevanssi indexing everything, so how do I apply the filters base on user-selected options in the search form? Any example code I can see? Any sites that actually do this kind of thing? I just can’t find anything,

    • http://www.mikkosaari.fi/ Mikko Saari

      If you want to use taxonomy filters, the best way is to create a tax_query (http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) and add it with relevanssi_modify_wp_query. Here’s a fairly thorough example. Doing a taxonomy dropdown is fairly easy (wp_dropdown_categories() helps a lot).

      If you want to adjust weights, then you must use the relevanssi_weight filter; the approach is similar, read the user-provided values from query variables and use them in the filter. I think that’s too much control to give for users: it’s lots of work for you to write, and 99.99% of users will never use it.

      Searchers in general just want to type words, anything more advanced is unlikely to see use.

      • Jason Judge

        How people will want to search will depend on the context. In my case I am indexing a second-hand record store. Depending on what they are searching for, they may want to lean towards a specific artist (in the artist taxonomy) or more towards a genre of music. They won’t be searching through big articles of text, but being able to find an artist that has been spelt ten different ways, will be very useful.

        So if I understand correctly, I nee to write my own query form and back-end, using the standard WordPress techniques, and Relevanssi will kick in and direct the query towards its own indexes? Or have I misunderstood?

        • http://www.mikkosaari.fi/ Mikko Saari

          Yes, you’ve got it. Relevanssi understands almost everything mentioned in the WP_Query documentation: tax_query, meta_query, post_type and so on.

          • Jason Judge

            Thanks, I’ll have a play.

          • Jason Judge

            I’ve not had any luck at all. I have tried adding a tax_query, as shown in your example link, and nothing is getting filtered. The example is quite a few years old now – is it still correct?

            I have this in my custom_search_filter:

            $query->set(‘tax_query’, array(
            ‘taxonomy’ => ‘artist’,
            ‘terms’ => array(‘foobar’),
            ‘field’ => ‘slug’,
            ‘operator’ => ‘IN’,
            ‘relation’ => ‘AND’,
            ));

            There is no “foobar” slug in the artist taxonomy, so I would expect everything to be filtered out, but no filtering is happening at all.

            If I can get this working, I don’t see any mention in documentation of WP_Tax_query supporting wildcards on taxonomy term names or slugs. Is that supported, since it is central to my original problem?

          • http://www.mikkosaari.fi/ Mikko Saari

            Looks like you’re one array too shallow: wrap your array() in one more array() and it should work.

            No wildcards in tax_query, it’s an exact match system.

          • Jason Judge

            Adding an array wrapper makes no difference. The query appears in the $query->query_vars array like this:

            ["tax_query"]=>
            array(1) {
            [0]=>
            array(5) {
            ["taxonomy"]=>
            string(6) “artist”
            ["terms"]=>
            array(1) {
            [0]=>
            string(6) “foobar”
            }
            ["field"]=>
            string(4) “slug”
            ["operator"]=>
            string(2) “IN”
            ["relation"]=>
            string(3) “AND”
            }
            }

            The fact that taxonomy terms cannot be searched using wildcards kind of defeats the main object of what I am trying to do. The user enters terms to search, and one option is for them to retrieve products that have taxonomy terms that match the keywords they have entered. I guess I am going to have to do a separate query to fetch a list of term IDs and then inject the IDs into the taxonomy filter (if I can get it to work).

          • http://www.mikkosaari.fi/ Mikko Saari

            Well, you can always use Relevanssi to search the taxonomy terms, then you can have wild cards. Tax_query is meant for dropdowns and exact match filtering anyway.

          • Jason Judge

            I thought I *was* using relevanssi using this filter? I’m confused.

            Back to the beginning: I would like the user to be able to enter keywords into a search box, and those keywords to be used to match against taxonomy terms in a custom taxonomy, and return all posts (type products) for those matching taxonomies.

            Can relevanssi, having indexed the taxonomies, support this, or not?

          • http://www.mikkosaari.fi/ Mikko Saari

            No – if you use tax_query, you’re not using Relevanssi. It is a direct MySQL query used to filter the results.

            What you need is automatically done, all you have to do is to check couple of boxes on Relevanssi settings to make Relevanssi index and search the taxonomies you want to search. Then all your searches will be checked against those taxonomies. No need to mess with tax_query.

          • Jason Judge

            Sorry, I thought relevanssi took what was given to the query, with any additions added to the query in the relevanssi_modify_wp_query filter then formed its own query based on what it was given. I must have misunderstood.

            If I set the global settings to only search in a single taxonomy, then what do I do for the next user that wants to search in a different taxonomy, and the user after that who wants to search in titles and post bodies? How do I change those search options per search, depending on what search options the user has ticked?

          • http://www.mikkosaari.fi/ Mikko Saari

            That’s a global setting, which you can’t modify per-user basis. Is it a huge problem if all searches match all taxonomies, post titles and bodies?

          • Jason Judge

            Yes, it is a problem, because it is not what the client wants. They can use Google for a one-search-fits-all. We are indexing locally using Relevanssi because we need more control.

          • http://www.mikkosaari.fi/ Mikko Saari

            Well, in that case what you want is not possible with Relevanssi.

          • Jason Judge

            I’ve worked around this problem now. When the search form is submitted with a second button called “artist_search”, that disables Relevanssi (two filters removed), empties the search term so it searches everything, fetches IDs of all the artist taxonomies that match the entered search term, adds those IDs into the query as a taxonomy join, then that fetches all products related to any taxonomy term that contains the artist name. Using the normal search button, and none of that happens so Relevanssi searches everything.

  • Justin Bell

    Hi, I am having issues getting relevanssi to use the AND relation when searching by both a custom tax and a category. what is the proper way to implement relevanssi_default_tax_query_relation?

    I have tried : add_filter(‘relevanssi_default_tax_query_relation’, ‘AND’);

    but nothing changes. I also tried to add it in a function simply as relevanssi_default_tax_query_relation (‘AND’); and that gives the white screen of death.

    Any help is much appreciated

    • http://www.mikkosaari.fi/ Mikko Saari

      You need to add a function to that filter, and that function needs to return “AND”. Like this:

      add_filter(‘relevanssi_default_tax_query_relation’, ‘isayand’);

      function isayand($relation) {
      return “AND”;
      }

      • Justin Bell

        Ah thanks, I shoulda realized that but was having brain lock.

  • http://www.macnative.com Randall Hinton

    I am trying to use your “relevanssi_pre_excerpt_content” or “relevanssi_excerpt_content” hook to modify the search results, but I cannot seem to access the post information inside my function… here is what I have currently…:

    add_filter(‘relevanssi_pre_excerpt_content’, ‘specificResults’);

    function specificResults($content, $post, $query) {

    return $post->ID;

    }

    Any help on how to get the post content for the search result would be helpful.

    Thanks,

    • http://www.mikkosaari.fi/ Mikko Saari

      What are you trying to achieve here? At least the filter function should return the $content variable, after the modifications you’ve done to it. If you return the post ID, you’ll ruin the whole excerpts.

      • http://www.macnative.com Randall Hinton

        Yes I understand it would ruin the excerpts, that was just me testing trying to get to the post content. What I am hoping to do, is that I have some LONG tabular data with product information on a few pages of the site I am working on for my client. If able to access the Post content I was planning on detecting the post ID, if it matched those with the product tables, then iterate through the content and present each table row in the results with a link taking the client to an anchor tag for the row they had searched for.

        The function reference above lists the $post as being passed through to the filter… but I cannot seem to access it.

        Thanks

        • http://www.mikkosaari.fi/ Mikko Saari

          Ah, I know what your problem is. Your add_filter() call is missing the last two parameters, and because of that, only the first parameter is actually being passed to the function.

          add_filter(‘relevanssi_pre_excerpt_content’, ‘specificResults’, 10, 3);

          should work much better.

          Do note that whatever data you put in the content in relevanssi_pre_excerpt_content will get mangled by Relevanssi excerpt-building algorithm.

          • http://www.macnative.com Randall Hinton

            Thank you Mikko, I am now able to access the Post data!

            One more question if you will indulge me, is there a way to disable the excerpt size limit from within the filter? or is there another filter hook that would give me access to that?

          • http://www.mikkosaari.fi/ Mikko Saari

            To modify excerpt length on the fly, use the “pre_option_relevanssi_excerpt_length” filter.

  • Dave Stromberger

    I’m trying to use relevanssi_default_meta_query_relation to change the meta query relation to “OR” from the default of “AND” that I have set in the admin panel, but Relevanssi returns zero results. Here’s my code snippit:

    add_filter(‘relevanssi_default_meta_query_relation’, ‘isayor’);
    function isayor($relation) {
    return “OR”;
    }

    I modified code that you posted in answer to another persons question. I want to leave the default set to AND, but under certain circumstances, switch to using OR.

    Thanks for your help!

    • http://www.mikkosaari.fi/ Mikko Saari

      ‘relevanssi_default_meta_query_relation’ sets the meta_query relation setting, not the general search operator that you set on the settings page. These are two completely different settings.

      Relevanssi Premium supports setting the operator on a per-query basis like this: http://www.example.com/?s=search+term&operator=OR – but that doesn’t work in the free version.

      • Dave Stromberger

        Thanks Mikko, looks like it’s time to upgrade to Premium!

  • max

    Does the relevanssi_default_tax_query_relation works in the free version?

    I see no change in if i use this code or not in the sql query string

    add_filter(‘relevanssi_default_tax_query_relation’, ‘relationAnd’);
    function relationAnd($relation) {
    return ‘AND’;
    }

    i need a search for the query and two taxenomys where the post has to be in both custom taxenomies

    • http://www.mikkosaari.fi/ Mikko Saari

      It does work in free version. Does your tax_query perhaps override it?

      • max

        right now it doesn’t i will look deeper into it and reply if i still get stuck.