Advertisment
AJAX(Asynchronous JavaScript And XML) as we all knows is a very democratic technology in web development that allows a web page to update the content without page reload or refresh. And WordPress is widely being used not just for Blogs but for CMS’s as well. I have used WordPress many times in my Projects and Built web applications by using WordPress as a CMS. While using WordPress for your websites or web applications you will need to use Ajax in your WordPress themes or plugins etc.
Today, I am going to show you how we can implement Ajax in our WordPress themes with the help of simple example.
Task:
Suppose Our task is to show the categories in a drop down box and upon selection of Parent Categories, Sub Categories should appear in another drop down box depending on the selection of main categories.
To achieve our task let’s take a walk through step by step.
Step 1:
At first, Create Categories: Parent and Sub as well as shown in figure below:
Step 2:
Create a template in WordPress( I am not going in details of what are the templates of WordPress and how they process in WordPress themes) in which we will implement ajax functionality. Open a new php file and save it with any name like I saved it with implement-ajax.php
Add the following code in the newly created page.
<?php /* Template Name: Implement Ajax */ get_header(); get_footer(); ?>
Above code is self-explanatory. Template Name: Implement Ajax is the name of the template in wordpress and functions like get_header(); and get_footer(); are used to display the header and footer of the page.
To add the ajax stuff you will first need to include the jQuery library file in your page. You can use any JavaScript library or can call ajax stuff with RAW JavaScript too. In our example we are implementing ajax with jQuery JavaScript Library which is very popular and very active in community.
Step 3:
Lets include the Jquery file in our template and call the wp_dropdown_categories function to retrieve the Parent list of Categories in a drop down.
<?php
/*
Template Name: Implement Ajax
*/
get_header();
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>
<style type="text/css">
#content{width:auto; height:400px; margin:50px;}
</style>
<div id="content">
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
</div>
<?php
get_footer();
?>
To understand about the arguments of wp_dropdown_categories look at here
I added second dropdown to display the sub categories in it.
Step 4:
Let’s add the Jquery code to get the ID of selected main category and then pass it on to the functions.php file where we will get the sub categories of that parent category ID and then send the results back to the page without refreshing.
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
// call ajax
$("#sub_cat").empty();
$.ajax({
url:"/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_action&main_catid=' + $mainCat,
success:function(results)
{
// alert(results);
$("#sub_cat").removeAttr("disabled");
$("#sub_cat").append(results);
}
});
}
);
});
In the above jQuery code we added the code at change event of main categories drop down with Id #main_cat.
var $mainCat=$('#main_cat').val();
.val() function gets the value of the selected option from drop down and stores in $mainCat variable.
$("#sub_cat").empty();
Now before calling ajax we will empty the sub category drop down #sub_cat with previous values if any.
Our next jQuery lines are for calling ajax jQuery Function. Look at the parameters of the ajax function below:
url:"bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST', data:'action=my_special_action&main_catid=' + $mainCat,
url parameter is used to make ajax working in WordPress. So, requests will be sent to admin-ajax.php file and then we will call the hooks in our functions.php file to get the posted data that is sent to the url:”/wp-admin/admin-ajax.php”
data parameter is used for sending the values along with request.
We have used 2 arguments with data parameter
1. action
2. main_catid
Step 5:
In functions.php file we will hook an action like below:
add_action('wp_ajax_my_special_action', 'my_action_callback');
above action hook has 2 arguments. Wp_ajax_[here will be the value that is sent with data parameter “action”] so it will be wp_ajax_my_special_action while second argument is the callback function which will process the data and send the results back.
Above action hook works with logged in users. Suppose you have something to show non-logged in users you can hook an action like this
add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');
what will be our final code after adding hooks for logged and non logged users and callback function
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$categories= get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
foreach ($categories as $cat) {
$option .= '<option value="'.$cat->term_id.'">';
$option .= $cat->cat_name;
$option .= ' ('.$cat->category_count.')';
$option .= '</option>';
}
echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
die();
} // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.
Step 6:
Now create a new page in the dashboard and assign the template to it like shown in the figures below:

Load the page in the browser and you will see first drop down with parent categories loaded in it.
Second drop down is empty and not loaded yet. Select any value from the first drop down and see how it works.
Summary:
This was a simple example I used for showing you how to implement the ajax in WordPress themes. You can fit this implementation of ajax in any of your needs. If you have any problems regarding WordPress implementation you can ask me in comments. I may come up with solutions in my next tutorials. So, don’t be afraid from developing advanced themes or use it as a CMS for your Projects.






hi,
I am a new for wordpress, and i want to know that where to make this implement_ajax.php file in theme folder?
Please help me….
Thanks in advance
One thing I noticed is that you cannot write an AJAX handler ONLY for the frontend;
In other words:
`add_action(‘wp_ajax_nopriv_my_special_ajax_call’, ‘implement_ajax’);`
will not work without the
`add_action(‘wp_ajax_my_special_ajax_call’, ‘implement_ajax’);`
Or rather everything will seem to be fine, but you will always get a response of 0.
Hi,
I keep getting -1 as the returned value. The id of the selected category is passed on to the javascript but the return from the function is -1. Any help would be appreciated.
Cheers
I’m actually getting the same problem with the “-1″ showing up.
At first I thought it was Wordpress saying there was no data to return or a similar error. It turns out I was returning the data in the PHP function when what I needed to do was echo it. As such, the data returns and displays fine.
It seems the “-1″ is related to whether or not the user is logged in. When I logged in, it changed to “0″. Still searching for a solution.
Ah, I figured out why it was showing the “-1″ and “0″. I had neglected to put in the “die();” at the end of the PHP function.
If your data is not showing up, it is likely due to mis-named functions or a typo in your code, probably not related to the “-1″/”0″ issue you’re seeing.
Thanks for this article!
Thanks, this helped me a lot. :)
Hi
I followed the tutorial. It was really helpful. I am not sure what am i doing wrong because my ajax call made successfully but it always return back “0″. Can you please suggest me how to debug it?
Thanks
[...] How to implement Ajax in WordPress Themes [...]
Nice. Am going to try this out. Isn’t adding code to functions.php a bad practise? Isn’t there an alternative for that?
that’s actually best practice. adding content to functions.php in your themes folder.
[...] How to implement Ajax in WordPress Themes [...]
[...] How to implement Ajax in WordPress Themes [...]
Hello, very great tutorial. I would ask if is possible have four dropdown menus…? Many Thanks!
[...] How to Implement Ajax in WordPress Themes [...]
[...] How to Implement Ajax in WordPress Themes [...]
[...] How to implement Ajax in WordPress Themes | Graphic and Web Design Blog Really good tutorial on Ajax in WP (tags: wordpress ajax tutorial howto webdesign template wp) [...]
great tips, has got me thinking of plans!
Great tut my friend, You can also checkout the article from Chris Coyier from CSS-tricks from last month: “AJAXing a WordPress Theme” http://bit.ly/aQjo9G
To prevent conflicts with other jQuery enabled scripts, you should really use wp_enqueue_script above the header to load jQuery.
.-= Jake Goldman´s last blog ..Will HTML 5 replace Flash in the next 5 years? =-.
Really nice tutorial, does adding ajax add overhead to blog load times? If you have particularly large amounts of categories? I also need to read more about creating wordpress templates.
.-= Dragon Blogger´s last blog ..What Are the Easiest Ways To Monetize Blog Traffic? =-.
Nice, but it would have been much more useful if it dealt with something more practical.
This is really a simple example. You can use it anyway you want !
Nice tutorial. I like this type: step-by-step, code and screenshots included.
But in this post, is it a mistake when you name the action “wp_ajax_nopriv_my_special_ajax_call” while in the code above you make a request with data: “data:’action=my_special_action&main_catid=’ + $mainCat”? I think it should be “wp_ajax_nopriv_my_special_action”.
.-= Rilwis´s last blog ..JS Slideshow, CSS Reference, Mã hóa dữ liệu, WordPress Custom Functions =-.
Yes, it is a typo mistake :)
very happy you pointed out it.
.-= Muhammad Adnan´s last blog ..FREE PSD to XHTML Conversion ($123 value) =-.
Nice tutorial
I hope can implement ajax in my blog
Thank you
.-= ebsoft´s last blog ..Simpan dan baca Google Map/Earth secara offline dengan GMapCatcher =-.
very useful guide! great! :)
[...] How to implement Ajax in WordPress Themes | Graphic and Web Design … [...]
Appreciate Efforts.
Great post, I am planing on implementing it on my personal Blog.. Tx