Why not helping your visitors to find what they’re looking for on your blog, by using a cool auto-completion on your search field? To do so, we’ll use Wordpress tagcloud, php and ajax.

Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn’t really optimized.

The idea

We will use tags as a list of keyword to suggest to the readers.

When someone will start to type on the search field, we will use Javascript to send a request to a php page which will do the following SQL request SELECT * FROM matable WHERE ‘name’ LIKE ‘$search%’. Via Ajax, we’ll send back the request results to our page, and display it to the visitor.

automcompletion-wordpress.png

First part: PHP

The first thing to do is to create a php page. This page will send a request to our WP database and display the tags as a html unordered list.

<?php
if (isset($_POST['search'])) {
        $search = htmlentities($_POST['search']);
} else  $search ='';
$db = mysql_connect('localhost','root',''); //Don't forget to change
mysql_select_db('wp', $db);		     //theses parameters
$sql = "SELECT name from wp_terms WHERE name LIKE '$search%'";
$req = mysql_query($sql) or die();
echo '<ul>';
while ($data = mysql_fetch_array($req))
{
        echo '<li><a href="#" onclick="selected(this.innerHTML);">'.htmlentities($data['name']).'</a></li>';
}
echo '</ul>';
mysql_close();
?>

This code is simple: It receive a POST parameter (The letter(s) typed in the search field by the visitor) and then sends a request to our WP database in order to gets all tags starting with the letter(s) typed in the search box.

Part two: Ajax

Now it’s time to start the client-side programming. We need to code 4 Javascript functions in order to make our auto-completion work:

  • Function ajax() will create a XMLHTTPRequest object.
  • Function request() will send an Ajax request to our gettags.php file.
  • Function return() will return gettags.php contents.
  • And the selected() function will update the search field.

Here’s our gettags.js file and the 4 functions needed:

var myAjax = ajax();
function ajax() {
        var ajax = null;
        if (window.XMLHttpRequest) {
                try {
                        ajax = new XMLHttpRequest();
                }
                catch(e) {}
        }
        else if (window.ActiveXObject) {
                try {
                        ajax = new ActiveXObject("Msxm12.XMLHTTP");
                }
                catch (e){
                        try{
                                ajax = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {}
                }
        }
        return ajax;
}
function request(str) {
	//Don't forget to modify the path according to your theme
        myAjax.open("POST", "wp-content/themes/openbook-fr/gettags.php");
        myAjax.onreadystatechange = result;
        myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        myAjax.send("search="+str);
}
function result() {
        if (myAjax.readyState == 4) {
                var liste = myAjax.responseText;
                var cible = document.getElementById('tag_update').innerHTML = liste;
                document.getElementById('tag_update').style.display = "block";
        }
}
function selected(choice){
        var cible = document.getElementById('s');
        cible.value = choice;
        document.getElementById('tag_update').style.display = "none";
}

Part three: Editing your theme

Now that we have our php and javascript ready, we can edit the searchform.php file from your WP theme:

Your searchform.php file should look like this:

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
        <div>
                <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
                <input type="submit" id="searchsubmit" value="Search" />
        </div>
</form>

We have to add a div, which will display the received data from the request, as well as a Javascript event on the search form:

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
    <div>
        <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" onkeyup="request(this.value);"/>
        <input type="submit" id="searchsubmit" value="Search" class="button" />
    </div>
    <div id="tag_update"></div>
</form>

Final part: CSS

Due to the fact that every theme use different color schemes, this is only an example. Anyways, I thought it could be a good start:

#tag_update {
        display: block;
        border-left: 1px solid #373737;
        border-right: 1px solid #373737;
        border-bottom: 1px solid #373737;
        position:absolute;
        z-index:1;
}
#tag_update ul {
        margin: 0;
        padding: 0;
        list-style: none;
}
#tag_update li{
        display:block;
        clear:both;
}
#tag_update a {
        width:134px;
        display: block;
        padding: .2em .3em;
        text-decoration: none;
        color: #fff;
        background-color: #1B1B1C;
        text-align: left;
}
#tag_update a:hover{
        color: #fff;
        background-color: #373737;
        background-image: none;
}

That’s all. You now have a very nice auto-completing search form! If you have any questions, feel free to leave a comment below.

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!
Digg This | Stumble it | Add to Del.icio.us | | Print This

There Are 29 Responses So Far. »

  1. 1 Mike Smith
    Wednesday, September 10th, 2008 at 4:53 am

    This is awesome. I’m going to implement it into a new theme I’m working on. Thank you for writing this tutorial up. Always with gems on this site, I tell ya :)

  2. 2 jbj
    Wednesday, September 10th, 2008 at 5:36 am

    Thanks Mike, I’m glad you enjoyed this tutorial!

  3. 3 K-IntheHouse
    Wednesday, September 10th, 2008 at 8:14 am

    Excellent post! I wonder if Google will push their suggest feature in Google Custom Search.

    Stumbled and delicioused.

  4. 4 Jean-Baptiste Jung
    Wednesday, September 10th, 2008 at 12:41 pm

    Indeed the suggest feature will be great in Google Custom Search! Thanks for your complimnts and for stumbling/deliciousing!

  5. 5 Kyle Eslick
    Wednesday, September 10th, 2008 at 2:16 pm

    Great post JBJ! Between your posts here and over at CatsWhoCode, you are really doing great work!

  6. 6 Jean-Baptiste Jung
    Wednesday, September 10th, 2008 at 5:08 pm

    Thank you Kyle! :)

  7. 7 Ronny Edwards
    Wednesday, September 10th, 2008 at 6:48 pm

    This is a really hack. Adding to my next theme project. Thank you jbj.

  8. 8 Drew Douglass
    Thursday, September 11th, 2008 at 12:31 am

    Hi,

    Just wanted to say this is a fantastic tutorial with very well written code, thanks a lot for sharing!

    Best Regards,

    Drew

  9. 9 MrBrown
    Thursday, September 11th, 2008 at 8:19 am

    in the ‘gettags.php’ file, you can put an include of ‘wp-blog-header.php’ file, so you have available the WordPress $wpdb database object and strip off all ‘mysql_*’ functions.

  10. 10 jbj
    Friday, September 12th, 2008 at 9:05 am

    @Drew: Thanks!

    @MrBrown: Thanks a lot for this. Now we can have optimized SQL :)

  11. 11 Alice
    Sunday, September 28th, 2008 at 3:00 pm

    Hi,
    this is really great!

    But I have a small question:
    I am using the plugin “Platinum SEO Pack”. That’s why a have a custom field called “keyword”.
    It’s possible to do your hack with my keywords (all the words I have in the custom field “keywords” in all posts together) instead of the tags?

    I don’t know exactly how to change your hack, so that “my” search-words (the keywords) will be display and not the tags…

    It will very nice, if you could help me!

  12. 12 Kyle Eslick
    Sunday, September 28th, 2008 at 5:16 pm

    @ Alice - The keyword field on that plugin is for meta keywords (which search engines use to learn what your post/page is about). It is not the same as tags and should be used in addition to tags.

  13. 13 John Miller
    Wednesday, November 5th, 2008 at 5:03 pm

    <input type=”text” value=”
    Fatal error: Call to undefined function the_search_query() in searchform.php on line 12

    Not working, I am getting following error on the html form. Looking in the php file there is no function named the_search_query();

    Am I missing somthing? Would it be possible to download all scripts, php and form files?

  14. 14 Nik Chankov
    Friday, November 28th, 2008 at 11:42 am

    I created a plugin for wordpress which doing the same thing - http://nik.chankov.net/autocompleter/, should be working out of the box.

    Thanks for the idea, because I’ve read about this here ;)



Leave A Comment