How to Implement Ajax in WordPress Themes

 Posted in Coding WordPress 682 days ago Written by: Muhammad Adnan
  • Buffer
  •  61
  • Buffer

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.

How to Implement Ajax in WordPress Themes

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:

how-to-implement-ajax-in-wordpress-themes

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:
how to implement ajax in wordpress themes

Load the page in the browser and you will see first drop down with parent categories loaded in it.

how to implement ajax in wordpress themes

Second drop down is empty and not loaded yet. Select any value from the first drop down and see how it works.

how to implement ajax in wordpress themes

ajax implementation in wordpress themes

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.

 Did you enjoy this article and found it useful?

Hi! I am Adnan, a Full time freelance developer who gets his hands dirty with php,xhtml/css,PSD Slicing and Conversions to Xhtml/CSS, jquery,wordpress,oscommerce and facebook programming. I am presently attending the great Virtual University of Pakistan to earn my MS in Computer Science by the end of 2010. Find out more about me at my blog and tweets
Free Website
 

 61 Brilliant Comments - Join Discussion Now!

  • Veronica

    Posted 13 hours ago
    61

    This was a great tutorial. I’ve read ebooks, tutorials, etc. on WP ajax and was about to give up when I stumbled on your tutorial. It was straight forward and I was able to finish my chained select boxes based on custom post type meta data with no problems. Thank you!

    Reply
  • Janvier

    Posted 9 days ago
    60

    Great piece of code to start from. However, I noticed you have a lot of typos which leads to all kinds of errors. If you could look into that, it’s be fantastic! I got it working and I appreciate the efforts indeed

    Reply
  • thinkdj

    Posted 12 days ago
    58

    On the last Code Snippet block, it should be

    add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);//for users that are not logged in.

    and not wp_ajax_my_special_ajax_call. Took me a while to find out why it was returning 0 always.

    Reply
  • Saul

    Posted 65 days ago
    57

    I have the follow Error: ¿Could you help me please?
    Fatal error: Call to undefined function add_action() in /httpdocs/site/wp-includes/functions.php on line 4569
    I have installed the WordPress Version 3.2.1

    My Code:
    function implement_ajax() {
    if(isset($_POST['estado_id']))
    {
    $pages= get_pages(‘title_li=&sort_column=menu_order&parent=’.$_POST['estado_id'].’&child_of=’.$_POST['estado_id'].’&hierarchical=0′);
    foreach ($pages as $pagg) {
    $option = ‘ID ) . ‘”>’;;
    $option .= $pag->post_title;
    $option .= ”;
    }

    echo ‘Scegli…’.$option;
    die();
    } // end if
    }
    add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);

    Reply
  • Beratz Gashi

    Posted 66 days ago
    56

    if somebody can post a video tutorial of this will help us more to beginners

    Reply
  • Alvin

    Posted 169 days ago
    55

    Hi super tutorial biut how to implement this in an existing theme ?
    I have found the following code in my theme , but what should be modified ?
    I am a total noob in php :(
    —————————————————————————————————————-
    <?php
    $select = wp_dropdown_categories( 'show_option_none=Select&show_count=0&orderby=name&echo=0&hide_empty=0' );
    $select = preg_replace( '||i’, ”, $select );
    echo $select;
    ?>

    —————————————————————————————————————-

    Hope someone can help me out here!

    Gr. Alvin

    Reply
  • Take

    Posted 173 days ago
    54

    How i can add this function in some other php file, not in admin-ajax.php, can i add in functiones.php inside my theme?

    Reply
  • Muhammad Adnan

    Posted 189 days ago
    53

    function my_special_ajax_call() {
    if(isset($_POST['main_catid']))
    {
    global $wpdb;
    $categories = get_categories(‘child_of=’.$_POST['main_catid'].’&show_count=1&hide_empty=0′);
    if(count($categories) > 0){
    foreach ($categories as $cati) {
    $option .= ‘term_id.’”>’;
    $option .= $cati->cat_name;
    //$option .= ‘ (‘.$cati->category_count.’)';
    $option .= ”;
    }}else{

    $option = ‘None’;

    }

    //
    echo $option;
    die();
    } // end if
    }
    add_action(‘wp_ajax_my_special_ajax_call’, ‘my_special_ajax_call’);
    add_action(‘wp_ajax_nopriv_my_special_ajax_call’, ‘my_special_ajax_call’);//for users that are not logged in.

    Reply
  • Sefo

    Posted 190 days ago
    52

    I’ve the “-1/0″ problem. I’m working with the downloaded files. with die(); at the end and all that corrections.

    As I can see, if i log as admin it works fine. But if i’m logged as editor or something else, the problem starts.

    Can somebody help me?

    Reply
  • Sefo

    Posted 190 days ago
    51

    IT WORKS!! Thanks a lot!

    Reply
  • Danny

    Posted 198 days ago
    50

    Hey,

    Is there a way to use this code to implement a custom taxonomy (category) ?

    I can get the first select box to show the classifieds_categories but the secon box stays blank..

    Thanks..

    Danny.

    Reply
    • Janvier

      Posted 9 days ago
      59

      To use a different taxonomy, on the get_categories(‘child_of=’.$_POST['main_catid'].’&hide_empty=0′); add taxonomy=YOURTAXONOMY where YOURTAXONOMY is the name of the taxonomy you want to use.

      All becomes get_categories(‘child_of=’.$_POST['main_catid'].’&hide_empty=0&taxonomy=YOURTAXONOMY’);

      Likewise, change 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’); TO 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&taxonomy=YOURTAXONOMY’);

      Reply
  • raju

    Posted 199 days ago
    47

    Can anyone solve the issue? I am having problem with the script. When the sub category is selected, it doesn’t display any article associated. I wonder if it needs a button to view the article of the selected category/sub-category.

    Reply
  • Tandil Ajedrez

    Posted 219 days ago
    44

    Existe any plugin for make the entire site in ajax?

    Reply
  • Gonza

    Posted 233 days ago
    43

    EXACTLY what i was looking for. You saved me long hours of hard work.
    Genius!!1
    Thank you thank you thank you

    Reply
  • Thiago

    Posted 236 days ago
    42

    To avoid returning ’0′ just add die(); before closing the php function implement_ajax()

    Reply
  • Shah Alam

    Posted 245 days ago
    40

    I use your code but in action page it does not make any call back data .so its return 0 would please explain to use it.

    Reply
  • David

    Posted 255 days ago
    39

    Hello Adnan,

    I have your code working successfully!

    Now I am wondering if there is a way to take the final Select to the child of the child categories?

    Dropdown One — Parent Categories
    Dropdown Two — Child categories of the selected Parent category
    Dropdown Three — (the end of the categories) the children of the sub category selected in Dropdown Two

    Can your example be modified to the next level — child of the child?

    Thank you so much for your kind reply?

    Reply
  • Kaleem Ahmad

    Posted 269 days ago
    38

    Any one got the solution, please let me know , I am stuck in this.

    Reply
  • Amer

    Posted 274 days ago
    37

    This is working fine for me but the frontend is returning 404 page if i’m not logged in. Maybe my permission to the wp-admin folder is preventing it from working

    Reply
  • abc

    Posted 337 days ago
    31

    I am always getting 0 as response. i created a sub- categories of the main categories still it show 0 always. Can anybody has the ability to help me.

    Reply
    • Shawn Janas

      Posted 287 days ago
      36

      Same here :(

      Reply
      • Muhammad Adnan

        Posted 213 days ago
        45

        Check the code I posted in comments.

        Reply
        • raju

          Posted 199 days ago
          48

          Hi adnan, I did copy and paste your code attached still there is no result when the drop down is selected. The sub category gets populated after the parent category is selected but when the sub category is selected, it does not do anything. Can you please help? Thank you.

          Reply
        • raju

          Posted 199 days ago
          49

          Ok I added javascript on step 3 as follows:

          var dropdown = document.getElementById("sub_cat");
          function onCatChange() {
          if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
          location.href = "/?cat="+dropdown.options[dropdown.selectedIndex].value;
          }
          }
          dropdown.onchange = onCatChange;


          Now, when the sub cat is selected, it shows the posts. It will be better if the drop holds the category on the option so that the user knows where they are.

          Reply
    • dusuarez

      Posted 204 days ago
      46

      There is a bug in code.
      On step 5, at lines 16 and 17, just change “my_special_ajax_call” to “my_special_action”

      Reply
1 2

 Add Your Own Brilliant Comment:

Tags allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

US