How to: Create an Ajax-based Auto-completing Search Field for your WordPress Theme

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.

  • Leave a Comment
  • How To: Creating a Custom Page Template

    Sometimes creating a page within WordPress can be frustrating because it reformats the post and will sometimes break links or cause things not to display correctly. It can also be difficult to display videos or buttons within a page if you use the rich text editor built into WordPress.

    One thing I typically do in these situations is to create a custom page template for certain pages where I need more control over how it displays. One example of this is my advertising page which was created using this method. I wanted to use Paypal buttons for each type of advertisement, and I wasn’t able to do this within the rich text editor that WordPress offers.

    So, here is what you need to do. As a quick note, you will need some very basic HTML coding knowledge to write your page by hand, and you will want to make a backup of your theme before attempting this for the first time.

    What I did was make a copy of the page.php file within my theme. That is because WordPress uses the page.php file when creating your themes pages. Rename the copy whatever you want, as long as it isn’t already in use (I just went with advertise.php in my situation). Now you will need to name the PHP file. Once that is done, go to the middle of the PHP file you’ve created and delete out the content code, which usually looks something like this:

    <?php the_content(__('[Read more]'));?>

    This code might vary a little based upon the theme you are using, so it may not appear exactly like this. Now, you’ll want to paste the text/code you want to use on your custom page. Once you’ve got it how you want it, you’ll want to upload it to your site.

    WordPress Page TemplateThe next thing you need to do is to create a new page in your WordPress dashboard like you normally would. Once you’ve created a title, leave the rich text editor blank and go to the Page Template drop-down box in the right menu. Locate the named page you created earlier in the drop-down menu and select it. Now publish your page.

    You’re done! Go check your site to see how it looks and make adjustments as needed.

    Hopefully I explained this well enough. If you have any questions, please post them below and I’ll do my best to answer them, or will update the post accordingly.

  • Leave a Comment
  • How To: Assigning a Name to Your PHP Files

    By default, WordPress displays your php files by whatever the file name is. That means if you name your file wordpress.php, that is how it will show in your WordPress editor. When working with page templates, or if you just want to keep your files a little more organized, you’ll probably want to give your templates names.

    Here is all you need to do. Paste the following code at the top of the file:

    <?php
    /*
    Template Name: WordPress PHP
    */
    ?>

    Now change WordPress PHP to be the name you want to use. Easy enough, right?  Tomorrow I’ll be posting a little more about page templates!

  • Leave a Comment