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:

<?php 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.

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', 'fix_query');
function fix_query($c) {
    return 2;
}

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

If you’re using a version older than 1.15.2

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

add_filter('relevanssi_get_words_query', 'fix_query');
function fix_query($query) {
    $query = $query . " HAVING c > 1";
    return $query;
}

Just add this code to your functions.php file.

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); }
}
  • Hector

    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.

  • Philip Treacy

    right, and where exactly is the search result template??

    • That depends completely on your theme, but typically it is search.php under Appearance > Editor (except in Twenty Eleven, which does it differently).

  • Ian Siemer

    How can I append the post_type within the anchor of the “did you mean” result?
    e.g &post_type=qa

    • You can’t, right now. Looks like I’ll have to make that possible somehow.

      • Did you ever get this working? We’re using Relevanssi for a mobile view and need to add a /m/ to the beginning of the “Did you mean” link url.

        • I’ll add a ‘relevanssi_didyoumean_url’ filter to the function.

  • Pingback: Improve The Poor WordPress Search | The Mogul Times()

  • 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(isset($_GET[‘s’]))
    {
    if (function_exists(‘relevanssi_didyoumean’)) { relevanssi_didyoumean(get_search_query(), “Did you mean: “, “?”, 5);}
    }

    • Yes, though you can use is_search() too to check if you’re on a search page.

  • Pingback: Add 'Did you mean' to WordPress Search | WordPress Specialist()

  • Nathan Zumwalt

    Is there a way to return multiple suggestions with “relevanssi_didyoumean” ?

    • No, not right now. It’s mimicing the Google behaviour, so I’ve never really even considered doing it any other way, but I suppose it could.

  • Your plug in is great!

    I’m using Genesis as my framework and can only edit the child theme. I don’t see a search results php to edit and add the code for “did you mean”.

    Does the premium require input of code or is the algorithm built in?

    beta version of our site is http://www.matthew1924.org which will replace http://www.missionfinder.org

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

    • TimmyB

      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

  • Joe Buckle

    Is there is a way to get the original word `relevanssi_didyoumean()` is making the suggestion for?

    • That would be the search query (get_search_query()), if I understood you correctly.

      • Joe Buckle

        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?

        • No, there is not.

          • Joe Buckle

            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

          • Well, nobody has ever requested such a feature before… so I think it’s just you =)

  • Kirf

    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,
    Kirf.

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

      • Kirf

        Hey thanks for the quick reply! and thanks for the solutions! Cheers!

  • Awais Munawar

    HI Mikko , I placed code as you mentioned in above article but didn’t get any suggestion.

    • Does that var_dump() trigger or not?

      • Awais Munawar

        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

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

  • Craig Misak

    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.

    • You can use the “relevanssi_didyoumean_url” filter hook to edit the URL, that should be fairly easy.

  • Jennifer C

    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 designsandcode.com). 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.

    • Fix the error in your code I mentioned in response to the other comment. Does that solve this problem as well?

      • Jennifer C

        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.

          • Jennifer C

            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.

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

          • Jennifer C

            Sure, will do.

  • Matttisss

    Hello,

    How can we translate “Did you mean:” in different languages?

    Thank you for your help

    • Just change the text in the function call, you can write anything you want in there.

      • Matttisss

        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

        • 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);
          }

          • Matttisss

            Thank you it works well! ๐Ÿ™‚

  • Alex Drobyshev

    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?

    Thanks!

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

      • Alex Drobyshev

        Thanks for a lightning-fast reply! Much appreciated.

      • Alex Drobyshev

        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.

        • Yeah, looks like the quotes are being passed as entities and that’ll cause some interesting results. I’ll fix that.

          • Alex Drobyshev

            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?”

          • 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

  • Ameer Salah

    Are the following changes correct?

    I don’t have any effect.

    Thanks in advance ๐Ÿ™‚

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

      • Ameer Salah

        okay I have a mistake, I am using my theme. so what I can do?

        • Just follow the instructions in this post.

          • Ameer Salah

            With what action I can replace it?

          • Sorry, don’t understand the question. Just add the code to the place on your template where you want the “Did you mean” suggestion to appear.

          • Ameer Salah

            man I red every word it the upper tutorial
            and get the same.

          • I’ve asked you this many times, yet you’ve never answered: have you checked that your search is powered by Relevanssi in the first place?

          • Ameer Salah

            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

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

          • Ameer Salah

            if you mean this I just enable it now.

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

          • Ameer Salah

            Thank you man, sorry for your time.
            Many thanks.
            I guess we will need the premium in the coming days

  • Karsten M Jensen

    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.

    • Yes, multisite or not doesn’t have any difference. It should give suggestions from the current blog.

  • Guest

    Hello,
    When i try did you mean it return ‘c’ character always, how can i resolve it?

    • Do you have enough material in search logs to provide suggestions?

      • ChennaiBala

        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?

        • No; it’s a security and profanity risk, and too complicated if done well. I’m not interested in doing that.