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.

  • http://www.blogthememachine.com Mike Smith

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

  • http://www.catswhocode.com jbj

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

  • K-IntheHouse

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

    Stumbled and delicioused.

  • http://www.catswhocode.com Jean-Baptiste Jung

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

  • http://kyleeslick.com Kyle Eslick

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

  • Pingback: How to: Create an Ajax-based Auto-completing Search Field for your Wordpress Theme « Rich Internet Applications

  • http://www.catswhocode.com Jean-Baptiste Jung

    Thank you Kyle! :)

  • Pingback: links for 2008-09-10 « Tom Altman’s Wedia Conversation

  • Ronny Edwards

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

  • http://creatingdrew.com Drew Douglass

    Hi,

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

    Best Regards,

    Drew

  • Pingback: How To: creiamo un autocompletamento in Ajax nel motore di ricerca di Wordpress! - Geekissimo

  • http://www.studio404.it MrBrown

    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.

  • Pingback: WordPress Weekend Resources - September 12, 2008 | Theme Lab

  • http://www.catswhocode.com jbj

    @Drew: Thanks!

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

  • Pingback: Links da Semana: Logos para Wordpress, Pesquisa em Ajax e etc | Wordpress Themes

  • Pingback: Ajax: Create an Ajax-based Auto-completing Search Field for your Wordpress Them | bloground - Blogging resources, themes and plugins for your development

  • Alice

    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!

  • http://kyleeslick.com Kyle Eslick

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

  • Pingback: 30+ (More) Most Wanted Wordpress Tips, Tricks and Hacks | Wordpress

  • Pingback: 30+??????WordPress????? | ??|??

  • Pingback: HackWordPress.com | CNET.ro

  • Pingback: Como crear un formulario de busqueda autocompletable con Ajax para wordpress | Labrys

  • Pingback: Collection of WordPress Hacks | WordPress Hacks

  • John Miller

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

  • http://nik.chankov.net Nik Chankov

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

  • Pingback: pligg.com

  • Pingback: You are now listed on FAQPAL

  • Pingback: Top tutorials week ending 02/21/09

  • Pingback: 70 Very Useful Wordpress Hacks & Tricks » De Web Times - Sharing Useful Resources.

  • Devilz

    hello

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

  • Kerberos

    Thanks, this is helpful!

    -Kerberos

  • Pingback: DSergio.com – Enlaces de interes #01

  • Pingback: Ajax search box -creaza in Wordpress autocomplete la casuta de cautare

  • Pingback: 100+ Awesome Resource list for Wordpress | WebSenseLogic

  • Pingback: Top 10 WordPress Hacks of All Time | Bitmag

  • Pingback: Top 10 WordPress Hacks of All Time

  • Pingback: Resources and links – 1 April 2011

  • http://www.bannerdesignwork.com karthimx

    Great search script for my wordpress theme. thanks.

  • boghy

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

  • http://www.whatsthebigidea.com David Radovanovic

    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?

  • Pingback: 10 Facebook Hacks For The Bloggers – Techs Blog

  • http://sanuja.com Sam

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

  • jible

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

  • Jazeb Butt

    Thanks aloot .
    This code has solve my problem.

    Regards
    Jazeb Butt

  • http://modestbuy.com/ Derek

    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!

  • David Hilditch

    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

  • MoNika

    awesome script :):)

  • sachin

    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