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.
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>';

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){
ajax = new ActiveXObject("Microsoft.XMLHTTP");
catch (e) {}
return ajax;
function request(str) {
//Don't forget to modify the path according to your theme"POST", "wp-content/themes/openbook-fr/gettags.php");
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
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'); ?>/">
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />

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'); ?>/">
<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 id="tag_update"></div>

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;
#tag_update ul {
margin: 0;
padding: 0;
list-style: none;
#tag_update li{
#tag_update a {
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: Adding a Store to Your WordPress Blog

    Depending on the type of WordPress blog you run, you may have an interest in building a small store into your blog.   I’ve found this is a great way to make some extra income to cover your blog costs while at the same time providing your readers with a useful resource.

    How to Add a Store To Your WordPress Blog

    The method I’m going to cover here is the method I use and have found a lot of success with.  It involves using a purchased software and eBay’s affiliate program to generate income.   Before I get started, I wanted to make one quick point.   This method is not for all blogs.  Because the generated income comes from being an eBay affiliate, this method is best applied to blogs that cover products or services that are regularly purchased on eBay.    Examples would be photography blogs (cameras and equipment), video game blogs (games and equipment), etc.   Things like celebrity blogs, make money online/affiliate marketing blogs, or personal blogs probably won’t find a lot of success with this method because it doesn’t relate well to an eBay product.

    In order to get started, you’ll first need to purchase the Build a Niche Store software (commonly referred to as BANS).  It has a one-time cost associated with it, but once you own the software, you get lifetime updates and you can use the software on unlimited sites.   The team behind BANS is incredible with both their dedication to updating the product as well as their support on their forums.   Owning BANS has really been a great experience for me.  The software has also developed a lot of trust over the past 2 years from its users, so it is a very safe investment.

    Once you’ve got your BANS license and downloaded the software, you’ll also get instructions on getting your first site setup.  It installs via a script so everything is really easy.  The only thing you’ll need to know how to do when purchasing this software is how to manually create a MySQL database (if you installed your WordPress software manually, you should already know how to do this).   You can always contact your web host to find out how to do this as well.

    You’ll want to create either a sub-domain or directory on your site where you want to place your new eBay store.   I generally use directories, but either should work the same.   Inside your new folder you created you’ll want to upload the BANS software and then visit the domain and go through the install.   If you run into any troubles on your first try, you can always consult the installation guide that comes with the product.

    How Do I Integrate Build a Niche Store (BANS) with WordPress?

    Now, BANS was not specifically created for use with WordPress, but was instead designed to run solo on a new domain name.   Fortunately, thanks to the hard working team over at The Niche Store Builder, you can now get WordPress themes that were specifically designed to integrate WordPress and BANS together.   In addition to creating their own unique BANS themes for WordPress, with Niche Store Builder you can also get BANS templates that were designed specifically for popular existing WordPress themes such as ThemeSpinner’s Chimera theme and Daily Blog Tips StudioPress theme.   You’ll get a matching skin for your BANS directory/subdomain and also a widget to display on the main site promoting some of your niche stores items.  These templates can be activated from the BANS control panel just like how a WordPress theme is activated.

    Here is a screenshot of BANS being used with the Chimera theme:

    And here is one for the popular StudioPress theme:

    I’ve been using this method on a few of my sites offering up cookbooks or whatever else is related to the content of the site and the income definitely helps cover domain renewals, hosting expenses, or whatever other costs come up.

    If you have any questions or run into any troubles, please let me know in the comments below!

  • Leave a Comment
  • How To: Add Social Bookmark Links to your Theme

    An essential step in your blog promotion is to have people voting for you on sites such as or StumbleUpon. So, why not make it easier to visitors to vote for your articles on social bookmarking sites? In this tutorial, I’ll show you how to create a fancy multi-widget to tell your readers to go vote for your posts.

    The problem

    Many visitors will not vote for you posts on digg or stumbleupon simply because they read and enjoyed it. They simply don’t think about it, exepted if they come from one of theses websites.

    Most social bookmarking sites provides widgets to add to your blog to provide your visitors an easy way to vote for your post. This is functionally good, but what about create something more personal, which will perfectly fit your blog theme colors?

    Creating the widget

    Let’s create our very own multi-widget. First of it all, download the sample image I created for you. It will serve as the background image in this example, but of course you can change it, or put a background color instead by using css.

    On my blog, I chose to display the multi-widget at the bottom of each post. Like this, the reader will only see it if he finished the article, and will probably vote for it if he liked.

    Open the single.php file from your blog theme, and paste the following code after your post:

    <div id="cwc-vote">
    <li><a href="<?php echo the_permalink(); ?>"> (<span id='<?php echo md5("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);?>'>0</span>)</a></li>
    <li><a href="<?php echo the_permalink(); ?>">Digg</a></li>
    <li><a href="<?php echo the_permalink(); ?>">StumbleUpon</a></li>
    <li><a href="<?php echo the_permalink(); ?>">Reddit</a></li>
    <li><a href="<?php echo the_permalink(); ?>">Dzone</a></li>

    We now got a list with links to directly post (or vote if already posted) articles to the following sites:, Digg, StumbleUpon, Reddit and Dzone.

    You can easily add others social bookmarking sites: I can’t guarantee that it will work for all sites, but basically, the link must look like this:

    <a href="<?php echo the_permalink(); ?>">

    CSS Styling

    For now, our multi-widget is fully functional, but a bit ugly. Happily, pasting the following CSS code to your style.css file will make the widget looks good.

        /* Don't forget to change the image path */
        background: #fff url(images/cwc-vote.png) no-repeat top left;
    #cwc-vote ul{
    #cwc-vote ul li{
    #cwc-vote ul li a{

    Adding live count

    You probably noticed the (0) next to the link. We’ll use the api so we can get how much times the post has been bookmarked by users.

    Paste the following code in your single.php file, below the multi-widget.

    <script type='text/javascript'>
    function displayURL(data) {
    var urlinfo = data[0];
    if (!urlinfo.total_posts) return;
    document.getElementById("<?php echo md5("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);?>").innerHTML = urlinfo.total_posts;
    <script src='<?php the_permalink() ?>&callback=displayURL'></script>

    It is also possible to get the number of digg, but it’s a little harder, especially for beginners. Anyways, if you’re interested about it, tell me and I should make another tutorial.

    Now, you have a working multi widget to nicely tell your readers to vote for your article. On a personal note, I just made my first ever digg front page during the time I was writing this post and I think this multi-widget helped a lot. I wish the same to all of you 🙂

  • Leave a Comment
  • How To: Changing the Default WordPress Gravatar

    If you’ve been with WordPress awhile, you’ll probably remember back in October of 2007 when Automattic purchased Gravatar.   The concept behind Gravatar had always been an incredible idea, but it had always lacked the time and resources needed to make it work.  Now that Automattic acquired Gravatar, it was pretty obvious that the service would be resurrected and would be a great fit for the WordPress platform.

    Earlier this year when WordPress 2.5 came out, a shift was made in the WordPress community from the widely popular MyAvatars plugin (which uses MyBlogLog avatars) to Gravatars.   In addition to being built into blogs, we were also given the ability to build Gravatars into your blog.  But, did you know that blog owners can now also create your own custom default Gravatar image?

    Over at Pro Blog Design, Michael has written a great tutorial explaining exactly how to add your own default Gravatar image, as well as provide some tips on how to make a good Gravatar default image.

    In order to add the image you’ve made, you just need to take your Gravatar code and add the image URL right after the comma:


    <?php if(function_exists(’get_avatar’)){ echo get_avatar($comment, 50 );} ?>


    <?php if(function_exists(’get_avatar’)){ echo get_avatar($comment, 50, '');} ?>

    Great tip Michael!  You’ll want to click over to see Michael’s tips on creating a custom “No Gravatar” logo for your website.

  • Leave a Comment
  • How to: Create an Archive Page for your WordPress blog

    In my opinion, all blogs should have an archive page: It allows your readers to quickly browse your blog and find what they’re looking for, and this page is also very good for SEO.

    Here’s how to create this page on a WordPress blog:

    Archive WordPress Plugins

    There’s many plugins which allows you to automatically create an archive page. The good thing is that you’ll have (almost) nothing to do, and the bad thing is that you will not be able to customize it a lot, or you’ll have to edit the plugin files, which is sometimes a bit too hard if you’re not a developer.

    On my blog in French, I use the Smart Archives plugin. Even if it gives me satisfaction, the loading time of the page is very long due to the amount of posts to be displayed simultaneously.

    If you want to use a plugin, you shall also give a try to Clean Archives, or Extended Live Archives, which allows numerous personalizations.

    Do it yourself

    WordPress allows you to create page templates, so it’s possible to create manually an archive page. This is what I chose to do on my blog in English,

    Before starting to code, you’ll have to choose between two different kinds of archive page. The first one will list all your posts, and will allow a direct access to every article you wrote. The only bad thing is that when your blog will have many posts, the list may be a bit too long.

    The second template, which is better for blogs that have been online since more than one year, will list your posts monthly and by categories.

    Your choice is made?  So let’s go coding!

    First we’ll have to create a new file and name it archives.php. At the beginning of the file, paste the following lines:

    Template Name: Archive page

    This php comment define a name for our template, and will later allows us to select it on WordPress Dashboard, when we’ll create a new page.

    First template: Listing all posts

    $posts_to_show = 100; //Max number of articles to display
    $debut = 0; //The first article to be displayed
    <?php while(have_posts()) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
    $myposts = get_posts('numberposts=$posts_to_show&offset=$debut');
    foreach($myposts as $post) :
    <li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    <?php endwhile; ?>

    Second template: Archives by months and categories

    <?php while(have_posts()) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <ul><?php wp_list_cats('sort_column=name&optioncount=1') ?></ul>
    <h2>Monthly Archives</h2>
    <ul><?php wp_get_archives('type=monthly&show_post_count=1') ?></ul>
    <?php endwhile; ?>

    After you chose one of the templates I shown you above and pasted it to your archives.php file, you just have to upload it on your wp-content/theme/yourtheme/ directory.

    Then, in WordPress dashboard, create a new page, name it “Archives” (or whatever you want) and select Archive page as page template.

    That’s all! You now have an archive page, which is good for both your reader and search engines crawlers.

  • Leave a Comment
  • How To: Finding Category Numbers in WordPress 2.5

    One of the disappointing changes in WordPress 2.5 was the removal of category ID numbers.   I thought this was just a minor oversight, but since the 2.5.1 upgrade this problem still was not addressed.

    If you are looking for a category number (this is most often needed for setting up the homepage of Magazine WordPress themes), here is a really easy way you can locate it until the WordPress team adds the category number display we all took for granted before:

    1) Go to Manage > Categories.

    2) Hover your mouse over the category that you need the ID of.

    3) Look in the lower left corner of your web browser for the ID of that category.

    Here is a screenshot example:

    Hopefully WordPress will again display the category ID in one of the future updates, but thankfully this workaround is really easy.

  • Leave a Comment
  • How To: Moving WordPress Within Your Website

    There are times when you may wish to move your WordPress installation from one place on your server to another.   This often happens when there is a change in the URL of your WordPress install, such as with blog redesigns, moving to a directory, etc.

    WordPress is actually very flexible, so it isn’t extremely difficult to do.  Here is the information you will need:

    1. If moving to a new directory, create your new directory.
    2. If moving to your root directory, make sure your root directory is ready for the new files (including the index.php file, the .htaccess file, etc.).
    3. Once your new home is ready, login to your dashboard and go to the Settings tab (under General).
    4. Update the WordPress Address field and Blog Address field to reflect the new location.
    5. Click Update Options. (Don’t view or open your blog until all steps have been completed)
    6. Move all WordPress core files to their new location.  This includes subdirectories!
    7. Update your Permalink Structure to show the new location (add new directory or remove previous directory).

    That should about cover it.   If attempted, you’ll want to allow some extra time for following all the steps carefully, as it is somewhat of a delicate process.   If you run into any problems, consult the WordPress Codex, which has some troubleshooting, etc.

  • Leave a Comment
  • How To: Creating a Print Stylesheet in WordPress

    Awhile ago I made a call out to the authors of Premium WordPress themes to start adding print stylesheets to all of their themes.   Some already do, but I believe in order to truly be premium quality, things like a print stylesheet and an author page should all be included.

    While building a print stylesheet for a new blog I am setting up, I realized that I hadn’t written a post here explaining how to create a print stylesheet yet, so consider this to be that post.

    What is a Print Stylesheet?

    A print stylesheet is an alternate stylesheet that should only be used when someone attempts to print a page off of your blog.

    How Does a Print Stylesheet Work?

    A print stylesheet is a separate stylesheet that will override any designated style.css code when someone attempts to print a page off of your website.  If a print stylesheet is created correctly, people printing a webpage will not also print the unnecessary elements, such as the header, footer, and sidebars.

    How do I Make a Print Stylesheet?

    First thing you need to do create your print.css file. This can be done by taking a blank Notepad (or similar) file and naming it print.css.  You can also make a copy of your blog’s style.css file and rename it, then remove the code within the copy.

    What Code Do I Put Into My Print Stylesheet?

    Depending on your blogs theme, this step will either be pretty easy or incredibly difficult.  Basically, we don’t want things like your header or sidebars to appear in your print stylesheet, so you’ll want to setup your print stylesheet to remove these elements:

    #header, #nav, #sidebar, #footer .noprint {display: none;}

    Depending on your exact theme and how the div id’s are setup, what you put here will vary.  In other words, use the above as a guide, but customize it to match your theme.  You can also use this method to censor out images and other unwanted elements of your post pages (if applicable).  Also, if you have your contact information in your footer, you may want to leave the footer on your prints.

    Next, you will want to expand your content section so that it looks decent when printed, instead of the content margins your standard style.css uses.  It will probably look something like the following:

    #content {width: 100%; margin: 0; float: none;}

    Now, to ensure that alternate colors are not picked up when printed, you’ll want to do something like the following to make sure it prints using black ink:

    a:link, a:visited {color: #000000}

    Because most people use white paper, this should make your printouts better looking.

    How To Tell Your Theme to Use the Print Stylesheet

    Once you’ve built and uploaded your print stylesheet, the next step is of course to tell your theme to use it when someone prints something!  This is probably the easiest step of all.  You’ll want to simply paste the following code into your themes header file (usually just below the standard style.css code):

    <link type="text/css" media="print" rel="stylesheet" href="<?php bloginfo('template_url'); ?>/print.css" />

    So, there you go!  Hopefully if you’ve followed these steps, and uploaded your new print.css file to your WordPress blog’s theme, anything printed from your website will look much better.

    Related Printing Posts:

  • Leave a Comment
  • How To: Fixing Popularity Contest Plugin for WordPress 2.5

    The problem(s): With some upgrades of the WordPress 2.5 branch, the Popularity Contest WordPress plugin is not working properly. Also, people trying to activate the Popularity Contest plugin on a brand new WordPress install are getting a fatal error or a “doesn’t exist” message when attempting to activate the plugin.

    The solution(s): I actually ran into this problem on a fresh install of WordPress. After several attempts, I was unable to figure out the problem myself. Thankfully, a quick Google search showed a post over at WPGuy which gave details on fixing both problems!

    Here is what you need to know if you have this problem:

    Fix problems with the upgrade to WordPress 2.5

    Open your Popularity Contest plugin (edit it) and search for this code:


    And replace it with this:


    Fix problems with a new install of WordPress 2.5

    In addition to doing the above, you need to search for the following code:

    if (isset($_GET['activate']) && $_GET['activate'] == 'true') {

    And replace it with this:

    if (isset($_GET['action']) && $_GET['action'] == 'activate') {

    I went through both of these steps on my fresh WordPress install and it fixed the problem perfectly!

  • Leave a Comment
  • How To: Adding an Email This Button to Your Blog

    In the past we’ve talked about how to add a print button to your WordPress theme. Today I wanted to give you the javascript code you need to create an Email This button on your WordPress blog.

    Before getting to the code, I wanted to first say that this code is designed to allow readers to click on the button and have it open up their default email software and create a subject and link that point to the post the reader is currently visiting. This code is not designed to allow readers to contact the blog author.

    If you are wanting your readers to be able to contact you, I recommend you use one of the many great contact form WordPress plugins available. You should never embed your email address into some HTML code because it will be picked up by spam bots. Contact forms prevent spammers from finding your email address. The other thing you can do is offer “EmailAddress AT EmailCompany DOT com” (which your email address information filled in) to avoid spammers.

    Okay, so back to the Email button code. Here is the javascript you will need:

    <script type="text/javascript">
    <!-- Begin
    function isPPC() {
    if (navigator.appVersion.indexOf("PPC") != -1) return true;
    else return false;
    if(isPPC()) {
    document.write('<a class="contact" HREF="mailto:?subject=Take a look at this page I found, ' + document.title + '?body=You can see this page at: ' + window.location + '" onMouseOver="window.status='Send your friends e-mail about this page'; return true" TITLE="Send your friends e-mail about this page">Email to a Friend</a>');
    else { document.write('<a class="contact" HREF="mailto:?body=Take a look at this page I found titled ' + document.title + '. You can see this page at: ' + window.location + '" onMouseOver="window.status='Send your friends e-mail about this page'; return true" TITLE="Send your friends e-mail about this page" rel="nofollow">Email This!</a>');
    // End -->

    This will create an email where the reader can enter in someone’s email address and send them a link to your post/page.

  • Leave a Comment