"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 //bassistance.de

Now let's play with some code

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

<script type=text/javascript src=js/jquery.js></script>
<script type=text/javascript src=js/jquery.autocomplete.pack.js></script>
<link href="js/jquery.autocomplete.css" rel="stylesheet" media="screen" type=text/css />

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:

<script type=text/javascript>
    var data = "Search Terms Separated With Spaces".split(" ");  

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:

    global $wpdb;
    $search_tags = $wpdb->get_results('SELECT name FROM $wpdb->terms');
    foreach ($search_tags as $mytag){
        echo $mytag->name. ' ';

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.

<script type=text/javascript src=PATH_TO/jquery.autocomplete.pack.js></script>
<link href="PATH_TO/jquery.autocomplete.css" rel="stylesheet" media="screen" type=text/css />
<!-- This goes in the head -->
<script type=text/javascript>
		var data = '<?php global $wpdb; $search_tags = $wpdb->get_results("SELECT name FROM $wpdb->terms"); foreach ($search_tags as $mytag){ echo $mytag->name. " "; } ?>'.split(" ");

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