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.

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.

Jean-Baptiste Jung is a blogger/web developer/web designer who lives in the French-Speaking part of Belgium. Jean-Baptiste maintains two blogs: Cats Who Code.com where he and other authors write about Web Development, Web design, Blogging tips and WordPress, and WPRecipes.com where Jean shares useful WordPress snippets on a daily basis. When he's not blogging or having fun with codes, Jean loves to spend time with his wife and cat, and traveling everywhere he can.

  1. Mike Smith says:

    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. jbj says:

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

  3. K-IntheHouse says:

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

    Stumbled and delicioused.

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

  5. Kyle Eslick says:

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

  6. Ronny Edwards says:

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

  7. Hi,

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

    Best Regards,

    Drew

  8. MrBrown says:

    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.

  9. jbj says:

    @Drew: Thanks!

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

  10. Alice says:

    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!

  11. Kyle Eslick says:

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

  12. John Miller says:

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

  13. Nik Chankov says:

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

  14. Devilz says:

    hello

    Any body help me?
    i face a problem in php code.

  15. Kerberos says:

    Thanks, this is helpful!

    -Kerberos

  16. karthimx says:

    Great search script for my wordpress theme. thanks.

  17. boghy says:

    I modified a function:
    function request(str) {
    //Don’t forget to modify the path according to your theme
    if(str != ”) {
    myAjax.open(“POST”, “http://programmingdb.net/blog/wp-content/themes/bluesteel-20/gettags.php”);
    myAjax.onreadystatechange = result;
    myAjax.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
    myAjax.send(“search=”+str);
    }
    }

  18. Thanks for the tutorial!

    Won’t

    “$db = mysql_connect(‘localhost’,’root’,”); //Don’t forget to change
    mysql_select_db(‘wp’, $db);

    leave a security hole in the file?

  19. Sam says:

    Thank you so much for the information. I will try this on my site as well.

  20. jible says:

    Can’t get the selection to return term into search box, any idea?

  21. Jazeb Butt says:

    Thanks aloot .
    This code has solve my problem.

    Regards
    Jazeb Butt

  22. Derek says:

    Hey, thanks so much for writing this tutorial! I thought I should share a modification that I made to the query. I added a LIMIT to the end of the string so that it shows only so many results instead of a whole page full of results.
    Query ==> $sql = “SELECT name from wp_terms WHERE name LIKE ‘$search%’ LIMIT 0,10″
    Again Thank You, this was very helpful!

  23. David Hilditch says:

    Thanks for this amazing article! I was expecting it was going to take me a few days to build an ajax search box for our site but this helped me get the basics up in a few minutes!

    All that’s left is to style the drop down beautifully – I’m adding images to the drop down to make it even better and even going to do multiple different searches – i.e. search products AND search blog material.

    Really really cool stuff – I look forward to finding more cool tips from your site.

    Cheers,
    Dave

  24. MoNika says:

    awesome script :):)

  25. sachin says:

    its not working in wp3.5.1 or i am unable to run
    1. i create gettags.js code in my theme change path also
    2. create a gettags.php in my theme folder copying your code and change configuration
    3. create searchform.php in theme folder
    4. copied css code in style.css in theme folder
    please help

Trackbacks/Pingbacks »

  1. How to: Create an Ajax-based Auto-completing Search Field for your Wordpress Theme « Rich Internet Applications says:
  2. links for 2008-09-10 « Tom Altman’s Wedia Conversation says:
  3. Links da Semana: Logos para Wordpress, Pesquisa em Ajax e etc | Wordpress Themes says:
  4. Ajax: Create an Ajax-based Auto-completing Search Field for your Wordpress Them | bloground - Blogging resources, themes and plugins for your development says:
  5. 30+??????WordPress????? | ??|?? says:
  6. Como crear un formulario de busqueda autocompletable con Ajax para wordpress | Labrys says:
  7. pligg.com says:
  8. You are now listed on FAQPAL says:
  9. Top tutorials week ending 02/21/09 says:
  10. DSergio.com – Enlaces de interes #01 says:
  11. 100+ Awesome Resource list for Wordpress | WebSenseLogic says:
  12. Top 10 WordPress Hacks of All Time | Bitmag says:
  13. Top 10 WordPress Hacks of All Time says:
  14. Resources and links – 1 April 2011 says:
  15. 10 Facebook Hacks For The Bloggers – Techs Blog says:

Tweetbacks »

Leave a Reply