How To Use Ajax in WordPress. a person checks their code on a Mac desktop

How To Use Ajax in WordPress

If you have an engaged and active customer base for your website, you might wonder how you can provide a truly interactive and enriched web experience for them. Offering real-time interactivity can be a big draw for your audience. 

Fortunately, Asynchronous JavaScript and XML (Ajax) is an approachable method of adding interactive features to your website. When it comes to WordPress, you can even simplify the process using an Ajax-based plugin. 

In this article, we’ll introduce you to Ajax and how it works. We’ll also walk you through getting started with Ajax in WordPress. Let’s jump right in! 

What Is Ajax and How Does It Work?

Ajax brings together a number of different programming languages, such as HTML, CSS, JavaScript, and more. In action, it works behind the scenes to take requests from a web browser, send them to the server, and transfer the results back to the browser. 

As a web user, you won’t know that Ajax is at work. You’ll simply get a highly interactive experience. On your own site, for example, you might use Ajax to accept likes on posts from users who are logged in, and display a real-time tally.

Why Is Ajax Useful?

With Ajax, users don’t have to reload a page to see certain changes to it. This means your site will stay fast, and deliver a smoother user experience. Since Ajax is efficient, sending only the data it needs back and forth, it can maximize bandwidth and avoid heavier data transfers. 

As web users, we reap the benefits of Ajax all the time. One example is Google’s autocompleting search function.

Other examples you might be familiar with include Facebook comments and Instagram likes. Ajax is likely at work anywhere you are able to interact with a web page and receive information in return instantly.

Getting Started with Ajax in WordPress

When it comes to WordPress, there are a few ways Ajax comes in handy. First, we’ll take a look at the Ajax URL and how to use it alongside WordPress function hooks.  

The Ajax URL in WordPress

Since WordPress uses Ajax by default in the admin dashboard, adding more Ajax functionality there is not difficult. If you want to use Ajax on the front end of your site, however, you will need to understand how the Ajax URL works. 

In WordPress, your admin-ajax.php file has a URL. This provides the information needed to send data for processing, and is vital to front-end Ajax development. WordPress employs a wp_localize_script()call to use the Ajax URL to connect JavaScript and PHP functions, as PHP can not directly mirror these without some help. 

How to Use the Ajax Action Hook in WordPress

WordPress employs hooks in its programming, as a way for plugins and themes to interact with the WordPress Core. Hooks come in two varieties: “actions” and “filters.” With Ajax, you’ll be using action hooks to execute functions. 

Actions enables you to add data to WordPress or change how it operates. With Ajax, you’ll use the action wp_ajax_(action). A custom function can then be hooked into this, to be executed during an Ajax call. 

For example, this WordPress sample code shows how an Ajax call and a JavaScript object can be combined in the same file to execute an action:


add_action( ‘wp_ajax_my_action’, ‘my_action’ );

function my_action() {
global $wpdb; // this is how you get access to the database

$whatever = intval( $_POST[‘whatever’] );

$whatever += 10;

      echo $whatever;

wp_die(); // this is required to terminate immediately and return a proper response

You can also create separate JavaScript files for your Ajax actions. You’ll just need to be sure to use the Ajax URL, so the calls don’t get lost. 

How to Use Ajax by Working With an Example Plugin (3 Steps)

If you want to experiment with Ajax, the best way is to build a plugin with it. Fortunately, there are many pieces of example code or bare-bones plugins out there that you can start from. For this example, we’re going to use some downloadable WordPress Plugin Boilerplate sample code.

Step 1: Create the Appropriate File Structures

First, you’ll need to name your plugin and create the appropriate file structures for it. The name must be unique, and not conflict with any other tool in the WordPress Plugin Directory. That’s because when a user uploads your plugin, it will go into their wp-content/plugins/ directory.

Once you’ve decided on a name, you need to create at least the following three files in your own wp-content/plugins/ directory:

  • plugin-name.php
  • plugin-name.js
  • plugin-name.css

You’ll want to put the .php file in your new plugin’s folder, and create separate subfolders for the JavaScript and CSS files to live in. All the files necessary for your plugin to function will need to be located in the same master folder. 

In the next step, you’ll see that the sample code we’re using comes with pre-created file structures. We think it’s important to understand how to start from scratch, however, and why your files need to be structured a certain way. 

Step 2: Choose Some Sample Code to Start With

Using a sample code file is a good place to start when trying out Ajax on your first plugin. You always want to double-check your sample code, however, to make sure it’s safe and doesn’t contain errors. 

As we mentioned earlier, we’re going to use the WordPress Plugin Boilerplate for our example. This sample code comes packaged with the files you’ll need to complete your plugin.

This sample plugin also adheres to WordPress’ coding and documentation standards. You can download the plugin’s .zip file from the boilerplate website to get started.

Step 3: Hook Actions into Your Code

The plugin sample code we’re using is built with Object-Oriented Programming (OOP). This helps programmers organize their code, and creates an easily sharable and reusable pattern of development.

Plus, the code comes packaged with all the files necessary for plugin development, including the activation and deactivation files in the /includes/ directory. You’ll also find it easy to locate the public-facing and admin-facing files as needed.

Let’s take a look at our sample plugin, by viewing the beginning of the plugin-name.php file: 


 * The plugin bootstrap file
 * This file is read by WordPress to generate the plugin information in the plugin
 * admin area. This file also includes all of the dependencies used by the plugin,
 * registers the activation and deactivation functions, and defines a function
 * registers the activation and deactivation functions, and defines a function
 * that starts the plugin.
 * @link    
 * @since             1.0.0
 * @package           Plugin_Name
 * @wordpress-plugin
 * Plugin Name:       WordPress Plugin Boilerplate
 * Plugin URI:
 * Description:       This is a short description of what the plugin does. It’s displayed in the WordPress admin area.
 * Version:           1.0.0
 * Author:            Your Name or Your Company
 * Author URI:
 * License:           GPL-2.0+
 * License URI:
 * Text Domain:       plugin-name
 * Domain Path:       /languages

All the information contained in this portion of the code is important for registering your plugin with WordPress. This is how the plugin directory will know what to display for your plugin. 

Now you’ll need to do a few things in order to connect all the dots, including: 

  • Make sure your Ajax URL is available to your script. You can use wp_localize_script() to accomplish that. 
  • Create a plugin name class with class Plugin-Name{} in your plugin-name.php file. This is where you will define your action hooks.
  • Create a corresponding JavaScript function in your plugin-name.js file.

One important element of the Ajax approach is defining who can use each function, especially when creating front-end interactivity. We’ll hook in a front-end action with some sample code from WordPress:

if ( is_admin() ) {
add_action( ‘wp_ajax_my_frontend_action’, ‘my_frontend_action’ );
add_action( ‘wp_ajax_nopriv_my_frontend_action’, ‘my_frontend_action’ );
add_action( ‘wp_ajax_my_backend_action’, ‘my_backend_action’ );
// Add other back-end action hooks here
} else {
// Add non-Ajax front-end action hooks here

Let’s take note of a few things in this example. First, these actions will be available to anyone on the site, whether they are logged into an account or not. That’s indicated by the ‘wp_ajax_nonpriv_()’ call. Second, you can see that there are also back-end, administrative actions being hooked in during the front-end actions.

To understand the process that takes place in this set of actions, it’s also important to know that my_frontend_action will trigger the PHP function my_frontend_action_callback().

Step 4: Test and Debug Your Plugin

Once you set up all the action hooks and corresponding functions you need, you’ll want to test and potentially debug your plugin (if there are any issues). Your web host might offer a debugging tool as a part of its hosting package.

Here at WP Engine, we provide the WP Engine Error Log to help you find trouble spots.

Our error log provides a color-coded walkthrough of any errors in your site’s code, and where they interact with our servers or other parts of your site. This makes troubleshooting a lot easier, whether you’re working with Ajax or something else entirely.

Explore Other WP Engine Resources and Tools

Now that you’re on your way to creating amazing WordPress plugins with Ajax, you might want to assess what other tools you’ll need. WP Engine offers a complete Digital Experience Platform (DXP), and is here to help you create new plugins for WordPress.

Whether you’re interested in our WP Engine Error Log so you can execute a bug-free plugin, or you just need solid and secure WordPress hosting, we offer a wide variety of plans and resources for you to use! 

Get started.

Build faster, protect your brand, and grow your business with a WordPress platform built to power remarkable online experiences.