AJAX is a powerful JavaScript technology used to create smoother user experiences. In the WordPress ecosystem, AJAX is prevalent and can be easily implemented in themes or plugins. However, the challenge lies in managing the various steps needed to ensure AJAX functions correctly. Here’s a checklist to save you hours when implementing or debugging AJAX in WordPress.
Implementation Overview
The implementation of AJAX in WordPress involves two main parts:
- JavaScript Part: Responsible for submitting the request.
- PHP Part: Responsible for processing the request.
Checklist for Implementing AJAX in WordPress
To get ajax working in your WordPress theme or plugin follow this checklist:
- Hook our callback functions to an ajax function
- Create a callback function
- Write a JavaScript to submit a request via ajax
- Localize our JavaScript
#1 Creating a function hook
To implement AJAX in WordPress, start by creating hooks. These hooks form the foundation for how we call our variables and functions. It’s important to note that the first attribute of the hook consists of two parts:
wp_ajax_ + YOUR_ACTION_NAME
wp_ajax_nopriv_ + YOUR_ACTION_NAME
YOUR_ACTION_NAME
This part is gonna be set in your JavaScript as data.action variable.
wp_ajax_
The wp_ajax_
hook is used for AJAX requests made by authenticated users, those who are logged into your WordPress site.
wp_ajax_nopriv_
On the other hand, the wp_ajax_nopriv_
hook is for AJAX requests made by unauthenticated users, those who are not logged into your WordPress site.
The second attribute is a name of a function called on ajax submit, which is configured in step #2.
#2 Create a callback function
A callback function is responsible for processing our ajax request. It is also responsible for verifying our nonce. Make sure that nonce name you are verifying matches the nonce name you have created during script localisation in step #4. The name of nonce to note is ‘action_nonce’.
#3 JavaScript to submit a request via ajax
First thing to note is the action name ‘our_action‘, the action name must match YOUR_ACTION_NAME part from step #1. Also very important to note a security_nonce value which in this example is: ‘our_app.action_nonce’.
‘our_app’ is a variable initialised during script localisation in step #4.
#4 Localize our JavaScript
These are the steps you need to take in order to localise your JavaScript file. Pay attention to variable names.
1. Enqueue script name (theme-scripts) and localise script name (theme-scripts) must match
2. During script localisation we are creating a JavaScript variable called ‘our_app’ which is accessible on the frontend, these variables are visible within the source code of the page.
This what is injected into your HTML: