Posted on

“Did you mean” suggestions

Relevanssi has Google-style “did you mean” suggestions for queries. There’s a difference between free Relevanssi and Relevanssi Premium on how this is done. Free Relevanssi bases the suggestions on logged queries by the users of the blog; the wisdom of the crowds, so to speak. That requires the use of search query logging to be on for quite a while (depending on the search activity) to get enough data.

Premium Relevanssi has a spelling corrector algorithm, which uses the blog contents to learn how to spell words (so if the blogger constantly spells something wrong, the algorithm thinks that’s the correct spelling and suggests it!). Premium needs no logging and gets better suggestions from day one.

To use the suggestions, add the following line to your search result template, preferably before the have_posts() check:

if ( function_exists( 'relevanssi_didyoumean' ) ) {
    relevanssi_didyoumean( get_search_query(), '<p>Did you mean: ', '</p>', 5 );

The first parameter passes the search term, the second is the text before the result, the third is the text after the result and the number is the amount of search results necessary to not show suggestions. With the default value of 5, suggestions are not shown if the search returns more than 5 hits.

If you’re adding the code inside a code block, just add the if block, not the PHP opening and closing tags.

Problems with suggestions

Sometimes the suggestions don’t work. I’ve noticed that a large enough database can cause the teaching algorithm to crash. There’s a fix for that, though. It’s simple: don’t use any of the words that appear only rarely the database.

This fix can be done using a filter hook relevanssi_get_words_having and modifying the query like this:

add_filter( 'relevanssi_get_words_having', function() { return 3; } );

Just add this code to your functions.php file. If it’s not enough, adjust “3” to a higher value, but that shouldn’t be necessary.

Adding the “Did you mean” in Genesis

In your child theme, add this code to your search.php template:

add_action( 'genesis_before_loop', 'genesis_add_didyoumean' );
function genesis_add_didyoumean() {
    if ( function_exists( 'relevanssi_didyoumean' ) ) {
        relevanssi_didyoumean( get_search_query(), '<p>Did you mean: ', '</p>', 5 );

Modifying the “Did you mean” URL

If you want to modify the URL produced by the function, you can use the relevanssi_didyoumean_url filter hook. For example, to add a post type parameter to the URL, you could do something like this:

add_filter( 'relevanssi_didyoumean_url', 'rlv_modify_didyoumean_url' );
function rlv_modify_didyoumean_url( $url ) {
    $url = add_query_arg( 'post_type', 'product', $url );
    return $url;

Automatic search for “Did you mean” corrections

If you want to make Relevanssi automatically search for corrected search terms if there are no results found for the original search term, you can do this (this only works in Relevanssi Premium):

add_filter( 'relevanssi_fallback', 'rlv_didyoumean_fallback' );
function rlv_didyoumean_fallback( $args ) {
    global $relevanssi_dym_fallback;
    $query  = $args['args']['q'];
    $query  = htmlspecialchars_decode( $query );
    $tokens = relevanssi_tokenize( $query );

    $sc = new Relevanssi_SpellCorrector();

    $correct       = array();
    $exact_matches = 0;
    foreach ( $tokens as $token => $count ) {
        $token = trim( $token );
        $c     = $sc->correct( $token );
        if ( ! empty( $c ) && $c !== strval( $token ) ) {
            array_push( $correct, $c );
            $query = str_ireplace( $token, $c, $query );

    $relevanssi_dym_fallback = $query;
    $args['args']['q'] = $query;
    remove_filter( 'relevanssi_fallback', 'rlv_didyoumean_fallback' );
    $return = relevanssi_search( $args['args'] );
    add_filter( 'relevanssi_fallback', 'rlv_didyoumean_fallback' );
    $args['return'] = $return;
    return $args;

This requires Relevanssi Premium 2.0. If the search term doesn’t find any results, this function gets triggered, runs the spelling corrector for the search query and does a new search with the corrected query, hopefully returning useful results.

If you add this code to your theme functions.php, it will work automatically, but the change is invisible: your search results page will still show the original search term. That may be confusing. In order to fix that, this function sets the global variable $relevanssi_dym_fallback and stores the corrected query in it.

You can use that global function on your search results template to figure out if the query has been corrected and then print out the corrected search result:

	global $relevanssi_dym_fallback;
	if ( ! empty( $relevanssi_dym_fallback ) && $relevanssi_dym_fallback !== get_search_query() ) {
      	echo "<h2 class='page-title'>Actually searched for: $relevanssi_dym_fallback</h2>";

Purging “Did you mean” caches

The word list used for the “Did you mean” feature is a big, heavy thing, and is cached for a long time (a month) for this reason. The caching is generally a good thing, but may cause problems when testing the “Did you mean” feature.

The easiest way to purge the cache is to simply delete the option where it is stored. The option is stored in wp_options database table and is called relevanssi_words. Remove the option, and Relevanssi will regenerate it the next time it is needed.

109 comments “Did you mean” suggestions

  1. This code was giving errors on WP Touch and I found this to work…

    From the suggested code (which works fine at least on my web theme):

    found_posts . ‘ hits. ‘;
    if (function_exists(‘relevanssi_didyoumean’)) { relevanssi_didyoumean(get_search_query(), “Did you mean: “, “?”, 5); }
    echo ”;

    if (have_posts()) : while (have_posts()) : the_post();

    I removed the last line, to this:

    found_posts . ‘ hits. ‘;
    if (function_exists(‘relevanssi_didyoumean’)) { relevanssi_didyoumean(get_search_query(), “Did you mean: “, “?”, 5); }
    echo ”;


    … and pasted it right before

    Hope this helps someone.

  2. For anyone out there using a purchased wordpress theme or a theme that does not have a standard search.php file you can look through the php files until you find the line: if( have_posts() ) : while( have_posts() ) : the_post();

    Above this you can put the did you mean php code but you may notice it on pages that you go to even if you did not do a search. To fix this do an if statement to check if the search was clicked:

    if (function_exists(‘relevanssi_didyoumean’)) { relevanssi_didyoumean(get_search_query(), “Did you mean: “, “?”, 5);}

    1. Andrew, you need to add it manually, both in free and premium. Genesis and other framework themes (like Thesis) do things in different way, which makes adding the feature more difficult. I’ve done it in Thesis, but not in Genesis, so I don’t know the exact procedure. If there’s a suitable action hook then it’s fairly easy, otherwise it’s going to be fairly difficult – that’s the price to pay for the overall ease of use with these kinds of themes, as some things are going to be much harder to implement.

    2. Hi Andrew,
      Did you ever get this working with Genesis? Would be great to hear one way or another, as I have the same problem.
      Cheers … Tim

      1. I probably haven’t explained it properly (sorry). Basically, a user can add more than one keyword. `relevanssi_didyoumean()` can accept these words and make a suggestion for a word that is incorrect. Is there a way to get that particular word?

          1. Cool, that’s fine. Thanks for responding. I can work around my problem but do you think it would be useful for others if we could return an array of original words and their suggestions? If so, I could look into creating a function. If not then it’s obviously just me that would need such a thing.:D

  3. Hey, awesome plugin! I have one problem with (free) “Did you mean” suggestion feature. I get a anchor element with src attribute set correctly but without actual text, so it looks something like this:

    Did you mean: NOTHING HERE

    Could you please suggest what could be wrong here? I tried this in few different themes and on few different servers and I’m running latest version of wordpress (4.3.1) and latest Relevanssi plugin (3.5).

    Thank you very much,

    1. There’s a bug in the code. I’ll push an update next week, but if you want a fix meanwhile, edit relevanssi.php and change the variable name “$suggestion” to “$closest”.

      1. Yes that var_dump() triggers , but it triggers when i type text in search field and submit the form . What i want is when i type on search bar it gives us the options

        1. Ah, you’ve misunderstood the feature. It only triggers when there are no results found. It’s not supposed to offer suggestions when you’re typing search terms; Relevanssi doesn’t have that feature.

  4. I have to have the did you mean include “&post_type=product” at the end of the request search request. I’m working on simply redirecting and some other failsafes. But though if this didyoumean could be modified somehow to have that included it’d be the fastest way to solve this problem and keep the did you mean feature active on my site.

  5. I’m trying to incorporate this feature into a client’s site, and I’m not sure what I’m doing wrong…

    I am using Relevanssi Premium, but as part of a Search & Filter Pro form (plugin from I am using a child theme of Woothemes Canvas, and I was able to get the suggestion to show up by adding the template tag to my loop-archive.php file.

    But if I type in a search that I know will not return results (a misspelled word, for example, like frehand instead of forehand – it’s a tennis-related site), the suggestion that is returned is always the same and never has anything to do with what I actually searched for. I always get “Did you mean: 50?”

    I’m not sure what I’m doing wrong, so any insight would be helpful.

      1. If you’re referring to the fix you mentioned below of replacing $suggestion with $closest in relevanssi.php, yes, I tried that and I still get the same result.

          1. Oh.. If you’re referring to your response to my post there, yes I found a solution for that, but that’s a different problem. That was about changing the link on the suggestion.

            The issue here is about the suggestion itself. The problem is that no matter what I search, the suggestion is always 50, so I’m wondering if I’m doing something wrong with the template tag

            if (function_exists('relevanssi_didyoumean')) { relevanssi_didyoumean(get_search_query(), "Did you mean: ", "?", 5);}

            which I put in my loop-archive.php file.

          2. The code is correct. I seem to remember someone else having a similar problem, but I can’t recall the solution. Since you have a Premium account, can you perhaps set me up with access to the site, so I could take a look at it myself? I also have an updated version of the didyoumean function waiting for the next version, we could try that if you contact me through Relevanssi support.

      1. Thank you for your reply but I mean if I have a multisites configuration with different languages, how can I translate by using .po file? (for instance, one translation in english, one in german, one in french…)

        Thank you

        1. Just change the text in the function call, and make it a translatable string.

          $didyoumean = __( ‘Did you mean:’, ‘my-text-domain’ );
          if (function_exists(‘relevanssi_didyoumean’)) { relevanssi_didyoumean(get_search_query(), “<p>$didyoumean “, “</p>”, 5);

  6. Hi Mikko,

    I noticed that when the search query contains multiple words with only one of them misspelled, Relevanssi suggestion outputs a single word instead of full query containing the correction.

    For example, “mizpelld word” query would produce “Did you mean [link]misspelled[/link]?” suggestion when the desired behaviour is “Did you mean [link]misspelled word[/link]?” Can this be addressed somehow?

    Also, is there a way to get the function to return the value instead of echoing it automatically?


    1. I’m aware of this; it’s already fixed in Premium, and will be fixed in the next version of free Relevanssi.

      Both versions do return the value, and the fifth parameter for the function is a boolean to determine whether the value is echoed or not.

      1. Noticed another issue (I am using the most recent Premium version): if you include quotes in your search words, the “did you mean” function encodes them incorrectly, &quote; instead of ". Both the label and link are displaying incorrectly.

          1. Noticed something else…
            If I search for “blooood”, it correctly suggests “blood”.
            However, if I capitalize “Blooood” in search, it suggests exactly what I entered… “Did you mean Blooood?”

          2. Good catch. The corrected word is being str_replaced to the search query, but if the original word is not in lower case, the str_replace won’t match it (as the corrected word is always in lower case).

            I’ll fix this in the next version; meanwhile, as a quick fix, you can change the str_replace() on this line (290) in relevanssi.php to str_ireplace():

            $query = str_replace($token, $c, $query); // Replace misspelled word in query with suggestion

    1. Assuming you’re using a Genesis-based theme, then yes. Are you? You can also test this by adding something like

      echo “testing did you mean”;

      in the genesis_add_didyoumean() function and seeing if that gets printed out when you do a search. If not, then the whole filter function is not running.

      Also, is your search actually powered by Relevanssi? If you disable Relevanssi, do the search results change in any way?

          1. man I just configure the settings and indexes and it work.
            for example I check product index and it started showing product results. but for did you mean it is not working

          2. Have you enabled query logging? The free version uses the search query logs to produce the suggestions, so you need to have logs enabled and filled with good searches in order to come up with suggestions.

            Premium version gets the suggestions from your search index, and gets you much better suggestions immediately.

          3. Yes. That’s why you’re not seeing any suggestions. You need to have good amount of user searches in the logs to see suggestions (or use Premium, to get good suggestions immediately).

  7. Will this work if I’m running Relevanssi Premium on a multisite installation?

    I’ve added the PHP code to the search template, but I do not get any results.

      1. can you pls create a “relevanssi widget” which can show recent search terms /
        random search terms, with option to link the search terms to posts or
        search results?

  8. Hi,
    I have the premium version of Relevanssi. I think there is a bug when relevanssi shows suggestions in “Did you mean”. First, when searching a term that doesn’t have any results, “Did you mean” shows the exact term as a suggestion (It couldn’t be like that, because this term doesn’t have results…). Second, after some debugging I found that in “relevanssi_didyoumean” function there is a incorrect “if” statement that prevents from the actual suggestion to be shown:

    if (count($correct) > 0) {
    $suggestion = $query;
    $suggestion_enc = urlencode($suggestion);

    “$correct” has the correct suggestion, but you’re setting the suggestion to be equal to the query that was performed in the search.

    I guess it should be like:

    if (count($correct) > 0) {
    $suggestion = $correct[0]; // The first correct suggestion
    $suggestion_enc = urlencode($suggestion);

    1. No, that’s not correct โ€“ if you look at the foreach loop above, the $query doesn’t actually contain the original query, but the query with all the suggestions replaced to it. Setting the $suggestion to $correct[0] would replace the whole query with just one correction.

      I can’t reproduce the problem: if I try to search for a non-existing term, I get an existing, nearby term as a suggestion, never the term I searched for.

      If you want to debug this further, what does the $correct array contain?

  9. is there a way to autocorrect and show results. Right now when I add the “Did you mean” code
    if (function_exists(‘relevanssi_didyoumean’)) {
    relevanssi_didyoumean(get_search_query(), “Did you mean: “, “”, 5);

    I get a link to the results… shouldn’t it just show the results of the suggested autocorrect term? Is there a way to do this?

    1. Well, it’s a design philosophy question whether it should directly show the corrected results or not – sometimes the autocorrect makes mistakes and doesn’t actually changes the correct spelling to something else, if it’s a rare word.

      But sure, you can do that. On the search results template, you can run relevanssi_didyoumean() in a way that doesn’t print out the results ($url = relevanssi_didyoumean(get_search_query(), "", "", 5, false);), then fetch the keywords from the URL, then run relevanssi_do_query() with those keywords and present those results.

  10. Awesome plugin. I just had one quick question. I’d like to change the “Did you mean” anchor link to have an ID on it, so I can target it with Javascript. Basically, I’m using this on a custom search form that is AJAX based, so when that search term is clicked, I need to run a function to display the new results, instead of sending the user to a search results page.

    Is something like that possible? Thanks!

  11. Hey Mikko,

    I’m hoping you could provide me the solution you gave the user on Feb. 2, 2016. The did you mean function is returning the same result, regardless of the search.


  12. Seems the comment’s html got sanitized…

    If I want the suggestions to all the time, even if there are more than 5 results, I can’t.
    I’ve updated it to 100 and they still won’t show.

    1. Sergio, thanks for the note about the typo; fixed that.

      If the suggestion doesn’t show up, that means the search term is fine and doesn’t need corrections. Relevanssi doesn’t have anything different to suggest.

  13. Hi Mikko,

    Is there any way to have Relevannsi Premium actually show the search results for the suggestion? For example, right now, if we search “chickn” it will say “Did you mean chicken” but then below that it will say “No results found.” It would be great if it can actually show results for “chicken” without the user having to click on the search suggestion.

    Is this possible?


    1. Andrew, this post now contains instructions on how to make that happen with Relevanssi Premium. With the free version, it’s slightly more complicated, I’ll have to look at that later; it probably needs an update to Relevanssi first before it’s reasonable.

  14. Hi Mikko,

    We’ve got this code implemented in our functions.php file, and it had been working great. However, now if someone searches for a word that is misspelled, we’re getting a 500 Fatal Error.

    PHP Fatal error: Uncaught Error: Class ‘SpellCorrector’ not found in …functions.php

    It is a problem on Relevanssi Premium 2.1.2 and 2.1.3.

    Any ideas how best to fix?


    1. Oh! Nevermind… I just noticed you changed the sample spell correction code above, and it uses a different class than before…

      $sc = new Relevanssi_SpellCorrector();

      Just edited our functions.php file and it’s working now.

  15. Hi, we are using this amazing plugin on the free version, and we have two questions:

    1. We just apply the ‘relevanssi_didyoumean’ in the custom search.php and nothing is printed. Its is not supported anymore in the free version?

    2. The premium version uses a better did you mean system but we like to know if is working well with polylang. I mean if we have ‘spanish’ as a language it would work?


    1. Marcel, yes, the did you mean suggestions are available to the free version. It does require a log of searches, so if you don’t have enough searches logged, it won’t return results.

      The Did you mean in Premium compares the search terms to what’s in your database, so it’ll work with any language, even made-up languages (and if you constantly spell something wrong, that’ll be the correction Relevanssi suggests).

      1. Hi! Perfect!

        Last question, The Did you mean comparison of the premium version is it capable of detecting language?. For instance if i search for term ‘englush’ in spanish and none of the posts in spanish has the word ‘english’ but some posts in english they actually have the word ‘english’, would return something? I’m expecting no results, so no suggestion.

        Thank you for your patience.

        1. Marcel, the Premium version just checks your index, it doesn’t know which words are in which language. So, if you search for “englush” in Spanish and you’ve set Relevanssi to only return results from the current language, Relevanssi will return no results and will then suggest “english”, which will come up with no results. So not the ideal solution, but Relevanssi simply doesn’t have the information about the post languages at that point. Adding support for that is possible, but may be too complicated and slow for the benefit gained. I’ll put that on my to-do list to consider.

          1. Hi!

            I’ll talk to my client if they don’t mind about this minor issue we will purchase the premium version.

            Thank you!

  16. Hi Mikko Saari,

    I’m using the free version, it’s really amazing plugin. I have a question, in the premium version, could we insert our own dictionnary (i.e. a list of common words) into the plugin? Because we have German and Swiss German languages, and some specific terms.

    Thank you!

    1. Minh Tue, insert in what sense? For “Did you mean” suggestions? It’s not necessary, Relevanssi will get the suggestions directly from your database, so they will match specifically what’s in there.

      1. Mikko, thanks for your quick answer, and it’s what I expected. My partner will purchase this premium version.

  17. Hello Mikko,

    first of all, thanks for this great plugin.

    I wonder, if there’s a way to add this feature without using a childtheme or modifying the search-results-template? Maybe a code-snippet we can use with the code-snippet plugin to make it secure for updates?

    Best, Daniel

    1. Daniel, that is the code snippet on this page โ€“ I don’t care how you get that on the page (whether it’s by editing the template, using a plugin, or creating a shortcode out of it), but that’s the code, and there’s really no other way to get the suggestions.

  18. Hi Mikko,

    Relevanssi is a great plugin, thank you for your work !
    I did read the comments on this page. You do explain that the free version is triggered “when there are enough data collected”. What does it mean ?

    I’m trying to implement the free version on a local website and I’m not sure if I’ll be able to do enough search to trigger it ?!

    By the way, I did check the log option.

    1. Jeremy, the suggestions are based on the successful searches in the logs. If there are not enough searches in the log, there won’t be suggestions. There’s no hard limit, because the more searches you have in the log, the more suggestions Relevanssi can provide. It’s probably hard to generate enough searches by yourself, it does require exposure to public.

      The Premium version is really much, much better.

  19. Hi Mikko
    Thank you for the plugin. It helped me a lot. I just have noticed that when using the didyoumean function it is assuming that people search for a single word not for a sentence. This caused a warning when calling the levanstein that the string is too long to be checked. Is there a turnaround on something like that?

    1. No, it’s not โ€“ Relevanssi tokenizes the search query and passes individual words, not the whole search query, to the Levenshtein function. The function has a limit of 255 characters, but it should be quite unlikely to bump into words that long โ€“ย or even search phrases that long.

      1. Ah ok. I see, Thanks for your reply. However I think that this depends more on user input. Wouldn’t it be better in this case to avoid sending a search query with more than 255 characters to the log table to avoid showing this error?

  20. Hi Mikko,

    first of all thanks for your great plugin!

    I have an issue with the “Automatic search for โ€œDid you meanโ€ corrections” function. It does not work for me. I have all your code snippets in the functions.php. The default “Did you mean” works perfekt. But there is no automatic redirect… can you please helb me out with this? Perchased your plugin today ๐Ÿ˜‰

    Thanks, Patrick!

  21. Hi Mikko,

    You plugin looks quite useful.
    However i am just not able to trigger the ‘Did you mean’ block on front end.

    Any help would be greatly appreciated.

    1. John, it’s not possible to post templates in the comment form here. Please post the template to a Pastebin or something like that.

      In any case, for the free version of Relevanssi to be able to generate Did you mean suggestions, you need to have search logging enabled and enough material in the log to work as a source for suggestions.

  22. Hi, I have Relevannsi Premium and implementing the ‘Did you mean’ option.
    I have only successfully got it working with one misspelled author name, but nothing else seems to work. E.g. If I were to type ‘aple’ should it suggest ‘apple’? Same goes for other common words – it does not suggest anything.
    Further, the $relevanssi_dym_fallback doesn’t seem to trigger even on my one working example.

    1. Stef, yes, “aple” to “apple” is a basic correction that definitely should work. Sounds like the “Did you mean” suggestions are not running correctly. Please drop me a message on the support page and show me what you’re doing with “Did you mean” in the templates, how have you implemented it so far.

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.