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.

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

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

75 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(isset($_GET[‘s’]))
    {
    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,
    Kirf.

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

      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?

    Thanks!

    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!

Leave a Reply

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