Category

How to use AJAX in WordPress themes?

I’m fairly experienced with using AJAX and its various jQuery shorthand implementations but have never implemented AJAX into a WordPress theme I’ve had to do quite a bit of Googling. I’m writing this post to show how I’ve implemented AJAX into WordPress.

In your function file, add the following code:

// this code is used to add AJAX URL
add_action(‘wp_head’,’ajaxurl’);
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = ‘‘;
</script>
<?php
}

Now let say you want to send data from front page to back-end for creating a user, you can use a code similar to this:

<script>
function createUser(){
jQuery(“.register-form”).hide();
jQuery(“.register-confirmation”).show();

jQuery.ajax({
type:”POST”,
url: ajaxurl,
data: {
action: “review_vote_ajax_request”,
post_id: “1”
},
success:function(data){
alert(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});

}
</script>

Now in your function.php file, you will need a code to receive data.

Few things to note:
1. WordPress requires you to explicitly make the AJAX function accessible to non-authenticated users. To enable the AJAX call to non-auth users, you must include action to explicitly enable this: wp_ajax_nopriv_review_vote_ajax_request
2. You also need to include the action to explicitly enable this for authenticated users: wp_ajax_review_vote_ajax_request

add_action( ‘wp_ajax_nopriv_review_vote_ajax_request’, ‘createUser’ );
add_action( ‘wp_ajax_review_vote_ajax_request’, ‘createUser’ );

function createUser() {
echo “Received!”; // Can add further code here
wp_die(); // You must include the following at the end of your PHP AJAX function

}

Was this helpful? Did I miss something? Do you have a question? Get in touch.