AJAX Requests in WordPress (Guide with Examples)

Most of the WordPress websites use AJAX to provide a smooth user experience in which the user does not need to experience page reloads. Learn how to make AJAX requests in WordPress with an example.

AJAX Requests in WordPress

WordPress itself uses AJAX requests in the background for various purposes like autosaving posts, locking posts, session keep-alive, dashboard updates, media uploads and more. In this post, we are going to implement WordPress Custom AJAX with an example.

 

WordPress and AJAX Requests

AJAX is a technique that allows web pages to communicate with the server in the background and receive a response from the server without reloading the page. In WordPress, AJAX requests are supposed to be made to a specific URL, wp-admin/admin-ajax.php. This URL then looks for two registered hooks: one for the logged-in users and another for visitor or non-logged-in users.

  • wp_ajax_*: This hook is used for logged-in users, if registered, the assigned callback function will be called to process the AJAX request for logged-in users.
  • wp_ajax_nopriv_*: This hook is used for guest users who are not logged into the website. If registered, the assigned function will be called to process the AJAX request for guest users.
 

How to Make AJAX Requests in WordPress?

Even though core features of WordPress are gradually moving to the REST API, admin-ajax.php remains widely used for back-end compatibility. There are many reasons a custom AJAX action could be added in WordPress, load content on scroll, WordPress AJAX search, search suggestion, submitting forms and more. We are going to add custom WordPress AJAX actions to track the page views of a single post/page. Implementing AJAX requests involves the following steps:

 

Step 1: Handle AJAX Requests in a Function

The first step is to create a function that will handle AJAX requests, process the request data and send a JSON response to the browser. This function can be added to the functions.php file of the active theme.

  • We first check the nonce value of views_counter_nonce using the check_ajax_referer() function of WordPress.
  • Next, we check if the post_id was not sent in the request, we throw a JSON response with an error message "Invalid Post" using the wp_send_json_error() function.
  • The next line of code retrieves the view count from post meta and stores it in the $views variable. We then increment this value by 1.
  • Finally, we save the updated views count using the function update_post_meta() of WordPress and we send a success response using the wp_send_json_success() function.
// Function to save views count as post meta
function save_views_count() {

check_ajax_referer('views_counter_nonce', 'nonce');

$post_id = absint($_POST['post_id']);

if (!$post_id) {
wp_send_json_error('Invalid Post');
}

$views = (int) get_post_meta($post_id, 'views_count', true);

$views++;

update_post_meta($post_id, 'views_count', $views);

wp_send_json_success(['views' => $views ]);
}

 

Step 2: Register AJAX Actions

Next, we register actions for AJAX requests and assign the function we created. This will tell the admin-ajax.php to execute our function when an AJAX request for the views count action is received. The following hooks can be added in the functions.php file of the active theme for both guest users and logged-in users.

add_action('wp_ajax_save_views_count', 'save_views_count'); 
add_action('wp_ajax_nopriv_save_views_count', 'save_views_count');
 

Step 3: Enqueue & Localize WP AJAX JavaScript

Next, we need a JavaScript code on the front-end of the website to initiate an AJAX request to the action hooks we added. For that, we enqueue our JavaScript file, which contains the code for the AJAX request. The following code snippet is doing:

  • We enqueue our JavaScript file views-counter.js, which contains the code for the AJAX request.
  • We add a condition check to localize our views_counter object on single pages only.
  • In the localize script, we add the ajax_url, nonce and post_id of the current post to the object. The arguments can be accessed in JavaScript by calling the views_counter object.
function views_counter_enqueue_scripts() {
wp_enqueue_script( 'views-counter', get_template_directory_uri() . '/js/views-counter.js', ['jquery'], null, true );

if(is_singular()) {
wp_localize_script( 'views-counter', 'views_counter', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('views_counter_nonce'),
'post_id' => get_the_ID()
]) ;
}
}
add_action('wp_enqueue_scripts', 'views_counter_enqueue_scripts');
 

Step 4: Send WP AJAX Request From JavaScript

Now that we have added our WP admin AJAX actions, enqueued the JavaScript file and object, we can now add the code to send the request from client-side to server-side request handling code.

  • We create a JavaScript file named views-counter.js for this post. The name and path can be modified according to your theme structure.
  • In the JS file, we place a condition at the top and check if the views_counter object is defined. If the object is undefined, this means it is not a singular page and the views_counter object was not localized.
  • Next, we initiate a jQuery AJAX request along with the action parameter, which is save_views_count, the same as our AJAX action hook we created. We also send the nonce and post_id from our views_counter object.
jQuery(function ($) {
if (typeof views_counter === 'undefined') {
return;
}

$.ajax({
url: views_counter.ajax_url,
type: 'POST',
data: {
action: 'save_views_count',
nonce: views_counter.nonce,
post_id: views_counter.post_id
},
success: function (response) {
console.log(response);
}
});
});

We now have a working and ready-to-implement code that will track the page view count of a single post type. If we want to show this view count on the page, we would show it like this:

$views = (int) get_post_meta( get_the_ID(), 'views_count', true ); 

echo 'Views: ' . $views;
 

Important Notes & Practices

When implementing an AJAX request in WordPress, there are a few important things to keep in mind and follow as a practice:

  • Never trust the client-side requests and always validate them with the check_ajax_referer() function.
  • Sanitize the raw user input values in $_POST using an appropriate function, like we used absint() in our example.
  • Always confirm the data exists in the database before adding or updating any post meta.
  • Use wp_send_json_error() and wp_send_json_success() for standardized JSON responses.

We demonstrated how to add AJAX requests in WordPress with ready-to-use code snippets. AJAX is one of the useful techniques for building interactive websites. It allows us to update data in the background without interrupting the user experience.