Enable Auto-Complete Search in WordPress Blog!

“One sometimes finds what one is not looking for”

This quote by Alexander Fleming explains all what I am going to share with you today. I am pretty sure that you are aware of Google Search Suggest and Yahoo Search Assist feature. This feature helps you effortlessly find exactly what you’re looking for. No doubt, it lists a few suggestions to keep the user looking for more and more.

As you type something in the search box, it automatically offers search terms and phrases in real time. How nice will it be to have the same feature on your website or blog. In this post, I am going to explain an easy way to add search suggestion feature on your WordPress blog or website.

Things You’ll Need

jQuery: You can download the lates version from jQuery.com
Autocomplete Plugin: Download this plug-in by Jörn Zaefferer from http://bassistance.de

Now let’s play with some code

Include this code within <head>..</head> tag.

Here I am assuming you are using “js” folder to keep all your java scripts and supported files. You may need to update the location of these files based on your folder setup.

 

Here’s the actual jQuery code to enable this feature on an input box:

Variable “data” hold the terms that you would like the user to see in the search suggestion list and $(“#myInputBox”) is the id of the search input box.

Let’s check out how we can automatically call WordPress tags in our search suggestions, using WordPress wpdb class:

Here I am using WordPress wpdb class to fetch all tags assigned to the posts.

Here’s the complete code to enable this feature on your WordPress blog. Just replace the folder name with actual folder and the jQuery selector $(“#myInputBox”) with the actual id of search input box.

Don’t forget to add your inputs in the comments section below.

66 thoughts on “Enable Auto-Complete Search in WordPress Blog!”

  1. Sammie says:

    excellent work buddy!

  2. Abhinav Sood says:

    Oh! So this is all to it?
    This was a feature I always wished I had on my blog when I had started writing so frequently about diverse topics that bloggers would generally be looking for.

    With each new post, the older (but still useful) ones got buried out of reach. Only if I knew at that time it was all so remarkably simple! ah..

    Thanks for sharing, CJ. This is an amazing tip :)

  3. Doesn’t the data query send all the tags to the client? Maybe I am reading that wrong. It appears to be sending the entire tag database to the user, and on every page load it repeats the process.

    What happens when your tag count grows to an unmanageable size?

    I am not sure this is a sound way to handle this.

    1. CSSJockey says:

      @Webstractions: Agree with your point here, However I only explained the way to do it. With MySQL WHERE clause you can restrict the tags as per the requirements.

      I visited your site and saw the tag cloud in the sidebar. Isn’t that widget doing the same thing?

      And its showing some tags that don’t make sense to me like some with () eg. wp_reset_query(), is_front_page() etc. I guess you can use the WHERE clause to restrict them from human eye. I’d be glad if that helps you.

      Regards,
      CJ

      1. Thank you for pointing out the restriction on the tag cloud. I limited it to the top 20. Probably will do away with it in the future and run it on its own page (like some are doing now).

        As for the wp_reset_query() tag, that was done consciously — that is to say, not for any search purpose. A WP coder would understand it better than other users. BTW, that term is hitting like crazy in search.

        You are correct in being able to apply a where clause to limit the results, but your example does not reflect that. It is an all-or-nothing example that I just wanted to point out.

        Another refinement that would be beneficial is to not have the auto-complete kick in until there are at least 3 characters in the input box. Or use “shortcuts” like Apple does — talk about a user friendly search box!

        With that said, I do realize that the point of the article was to display how easy it is to jQuery the thing. On that aspect, you did well.

  4. Henrik says:

    Thanks for the great article. I try to search out content in the blog with this, but can´t get it to work..

    [code]
    $(document).ready(function(){
    var data = ‘get_results(“SELECT post_content FROM $wpdb->posts”); foreach ($search_tags as $mytag){ echo $mytag->post_content. ” “; } ?>’.split(” “);
    $(“#search”).autocomplete(data);
    })

    [/code]

    1. CSSJockey says:

      Hi, I hope you have followed all the steps mentioned in this article. Make sure that “#search” should be the ID assigned to the search input box.

      I have it working on one of my clients website. Share your blog’s url so I can check for possible errors.

      1. Henrik says:

        Hi, I´ve installed it locally on my computer :)

        I think the problem is that I will search för post_content, because with your examle it works (tags). I´m not that good at programming but I understand that I need to extract just the term of my search that is in the post and not the whole post. Eg search in all my posts, headlines and tags and get the result in the dropdown.

        …”echo $mytag->”the term”

  5. julien says:

    Hi CCSJockey,

    I have a little issue !
    Could you have a look to this page :
    http://www.jguiss.com/annonce-bon-plan/

    I have configured your auto-complete search script to my TAGS input
    But it’s doesn’t work !

    All is charged, CSS, JS, the url arl fine, the ID identifier is ok… but something is wrong.

    Thanks in advance

    1. CSSJockey says:

      Hi Julien,

      I checked the code, you have included jquery.js three times so first of all please call it only once.

      The auto-complete plug-in might be conflicting with some others you are using. Please remove other scripts one by one and see which one is causing issues,
      then we can check the variable and code for both to make it compatible with each other.

    2. Jitendra says:

      hi,
      your page link url is going to not found title.

      mention the correct URL

      Thanks
      raj

  6. Hi Mohit, thanks for the article. Its great and really helpful.

  7. mssmotorrd says:

    It’s the first time I commented here and I must say you share us genuine, and quality information for bloggers! Good job.
    p.s. You have a very good template for your blog. Where did you find it?

    1. CSSJockey says:

      Thanks, I appreciate your feedback. CSSJockey’s layout is a custom wordpress theme and I created it myself from scratch ;)
      Let me know if you need one for your website.

  8. Karl W says:

    Hi CJ,

    Thanks for the post, great work!

    I was wondering if you could show how i could manipulate this to just search post titles?

    I am trying t integrate it into a WordPress website that i am creating as a directory and would like the search to show business names as they are typed.

    Thanks!

    1. Karl,

      Saw your comment and thought of one possibility – taxonomies. Taxonomies are basically tags anyway, but can be categorized for just the purpose you need it for.

      1. Karl W says:

        Thanks for that, how would i add taxonomies and integrate with the search?

        Thanks again

        1. Karl, to get the taxonomy terms you would change the Select clause to:

          $search_tags = $wpdb->get_results(‘SELECT name FROM $wpdb->term_taxonomy‘);

          Setting up taxonomies is pretty straight forward. Justin Tadlock has a nice post on using them with lots of helpful info. See his Custom taxonomies in WordPress 2.8 article.

        2. Karl W says:

          Thanks again for your comments, taking a look at the link you posted now.

          I am thinking of using a few taxonomies for my website, is there a way to get it only to search one set?

          for example, i will have location, services etc… is there any way to configure it to search location.

          Thanks again for your help.

        3. Sovas says:

          Thank got you can not make it happen – If these things JS could do, then 100% pages would be hackable.

  9. Ayaz123 says:

    Hi,
    Thanks for an interesting post. Keep up the good work.

  10. Gary Calpo says:

    If apostrophes show up in the mySQL results, the javascript will break.

    I fixed it by replacing:
    $mytag->name

    with:
    str_replace(“‘”,”‘”,$mytag->name)

  11. David says:

    This is beautiful! Karl asked question how to populate the search just using one taxonomy (e.g., location). What should be modified here?

    $search_tags = $wpdb->get_results(’SELECT name FROM $wpdb->term_taxonomy‘);

  12. Is there a way to make the autocomplete return custom field values?

    That would be sweet :)

    1. Mohit Aneja says:

      Yes you can, All you need to do is modify the WordPress query to call custom fields.

  13. Anyone have suggestions on how to make this read from a custom table I created? I made a table called “wp_cities” and have city/state listed in there. I’ve tried every combo I could think of!

    Any/all help is much appreciated!

    1. Mohit Aneja says:

      Hi Mike, this page has a lot of information about using wpdb class to fetch data from WordPress tables. I hope this will help.
      http://codex.wordpress.org/Function_Reference/wpdb_Class

      1. Thanks Mohit! Much appreciated!

  14. betclic says:

    thank you admin for the info.

  15. Artem says:

    Mohit, this is nice, your example is very close to what I did. I have a question. What do you think would be the best way, to autocomplete the “next” word. Like if a user already got the first one in, dropped a comma, and wants to put additional tags in. Whats the best way to autocomplete additional names?

  16. Hi and thanks for the example. I’ve got this working, but why are you searching for tags and not the actual content? I would never search tags, and I given the lack of tag clicking I see on my blog or that of my clients, I suspect few others do either.

    Is there any chance of posting the code for the query that searches the actual post content and titles? This would be far more useful.

    1. CSSJockey says:

      This demo shows how you can enable this feature, You can modify the code to run any query as per your requirements.

  17. WordPress is the best blogging platform ever. It is much better than Typepad and blogspot.~;”

  18. DRM says:

    Heya!
    This was great, I managed to make it work. After some investigation and such, I’m still wondering..

    Imagine Ive got a portfolio, with a piece called “M.D. House”, and a category called “Concept Art” or “Fan Art”. How do I specify the query to make all of them work? So when you typed in “Concept”, you automatically get a next word, in this case “Art”..

    Or if you write “M”, that the letters keep adding up behind it..

    So it’s not limited by only 1 word.

    Wow, am I making any sense? :P

    DRM

    1. CSSJockey says:

      The query in the code is for tags, however you can update or write queries for categories as well. You might need to write a Javascript code If you wish to restrict users input to allow only the mentioned keywords.

  19. George says:

    Thank you for this cool tip. I implemented it on a site http://shoppingjar.com it was working at first but now it has stopped working.

    I tried deactivating all the plugins to check for conflicts but to no avail.

    Funny enough it works on my local webserver on my computer but not on the live site. any ideas?

    1. George says:

      Eureka!! Found the answer form the comment by Gary Calpo. It was the apostrophe in a tag.

      I think you should include it into your code!

      I have a question, my tags have more than one word but the tag selection only shows up one word. how can i have the whole tag come up in the suggest box?

      Thank you for your help.

      Cheers.

  20. Desha Rogers says:

    is any one else having problems styling the list? if you have figured it out please share. Thanks.

  21. sk8erbryan says:

    Thank you so much for this post. I was expecting something like this to be a lot more complicated and a lot more work, but I had it going on a site I’m working on in just a couple minutes

    I’ve got an issue though that I was wondering if anyone else has addressed. Does this handle phrases? It seems to get the first word of whatever tag I add and leave off the rest. So a tag of “Test tag” only shows “Test” any easy work around for this?

    Thanks again.

    1. CSSJockey says:

      It depends on how you split the keywords..

      1. Maglouard says:

        aah, not a problem. Good thing is I was inoklog for people who have blogged abt this plugin and i luckily landed here. Main thing is it helped me knowing the problem and since its my first plugin, I expect a lot more infact

  22. WMWeblog says:

    Hey. Thanks for the great solution. Can this technique also be used to say get suggestions from custom taxonomies for other types of fields then search as well?

    Thanks!

    1. CSSJockey says:

      Yes, you just need to update the query and jQuery code to achieve whatever you want.

    2. Rehman says:

      Hey thr,Thanks for posting this fix, but I was wnidernog why didn’t you commented this bug on the plugin page Anyways I for chance stumbled on your page and shall fix this bug in future releases.Thanks again,Abhinav

  23. Katie Dawson says:

    Your CSS3 articles are brill! Thank you so much for sharing your tips, excellent resource! :)

  24. Rod says:

    It’s great but … I have 5000 tags.

    The question is … is it possible to put all these tags inside an external JS ? once cached, it’s OK …

    Thanks !

    1. CSSJockey says:

      This might take a little longer, you can use Ajax instead of getting all tags with one query.. For AJAX this code won’t work, you might need to write custom code..

    2. Miki says:

      Couple of notes is_site_admin is depecrated; use is_super_admin iesantd. And, on the email users page I only seem to be getting 50 users, though I *believe* the emails are going out to all. Will have time to do more testing later this week has anyone seen this 50 user thing before, though?

  25. The code and scripts are very clear for a better application. On the other hand, you give the details of each script that is very good.

  26. Jim smith says:

    Could you please provide a step-by-step implementation process?
    It is not clear to me which wordpress file with a tag should get the first code segment (the one with autocomplete.pack.js), or which wordpress files should we insert other code segments (such as the one with myInputBox) into.

    Thanks.

    1. CSSJockey says:

      You would need to get the tags via PHP, you can create a function and return the string or directly implement the code to get tags in header.php file. The JavaScript in header needs the tags as string as shown in the example.

  27. Hello Mohit and team,

    Thanks for your excellent suggestion and code. Why don’t you make it as readymade wordpress plugin?

    1. Mohit Aneja says:

      Thanks, I’ll consider the same.

  28. kk says:

    actually how can i use the code in blogspot please help me out sir

    1. Mohit Aneja says:

      No idea about blogspot, I don’t code for the same and have no knowledge on that service.

      1. Lipovanu says:

        Hey scribu,Great tiratuol and I appreciate the updates that include Mike’s code. I tried the latest SQL code, but when I sort a column ASC/DESC entries that are NULL disappear after the page reloads with the new sort even though taxonomy IS NULL is included in the WHERE clause.

  29. kk says:

    hi sir but how i can use in google blogspot site

    1. Mohit Aneja says:

      It says wordpress blog so the code is for WP. I don’t think blogspot is that flexible to create these kind of features.

  30. sangram says:

    I am following this code for my blog.I used it at plugin and template file in theme.It is not working for me.

    Any one is there or helping me..

    Thanks sangram

  31. pulse says:

    great tutorial……thanks,

  32. dan says:

    thanks your post. it made me headache !

  33. Mahmoud says:

    MOHIT ANEJA THANK YOU SO MUCH YOU JUST MAKE MY DAY

  34. Martin says:

    Hi Mohit, thank you for this article. I tried to implement your code, but there is no autocompletion in my search field.
    ———————————————–
    wp_enqueue_script(‘jquery-ui-autocomplete’,’/wp-includes/js/jquery/ui/jquery.ui.autocomplete.min.js’,array(‘jquery’));
    function autocomplete_searchfield(){ ?>

    var data = “Search Terms Separated With Spaces”.split(” “);
    $(“#s”).autocomplete(data);

    <?php }
    add_action('wp_footer', 'autocomplete_searchfield',300);
    ————————————————-
    The link to the jquery-autocomplete script is in the html code of the page. After that your javascript appears. The search field has the wp-standard id "s".

    But why does it not work?

  35. Junaid says:

    Can you please tell me how can I search only post titles.

    1. Mohit Aneja says:

      You need to supply the data you want to search in the Array and it will show the same.

  36. Mike says:

    it’s really nice post. Karl, Saw your comment and thought of one possibility – taxonomies. Taxonomies are basically tags anyway, but can be categorized for just the purpose you need it for.

Leave a Comment

Your email address will not be published.*

*