WP REST API vs admin-ajax.php vs Must-Use Plugin: Handling AJAX Requests in WordPress

Read Time:12 Minute, 35 Second

The WordPress REST API was merged into WordPress core in version 4.7. Before that, developers relied on the default AJAX implementation, otherwise known as admin-ajax after the /wp-admin/admin-ajax.php file that processes AJAX requests in WordPress.

Since the introduction of the WordPress REST API, many plugin developers have started converting their plugins to use the REST API instead of AJAX. Aside from being newer technology, the REST API is considered a better option because less of WordPress core is loaded during a typical REST request, and a REST response is always in a predictable format based on its schema. However, is it faster than an AJAX request? Is there another option if the raw performance of your asynchronous requests is critical?

In this article, we’ll compare the pros and cons of each approach. We’ll also run some benchmarks to see which is faster, as well as look at how you can speed up your request processing.

There’s Life in the Old Dog Yet: AJAX

AJAX support in WordPress, in the form of the admin-ajax.php file, was added in 2006 as a way to process a few admin UI functions without annoying page reloads. It was also heavily used by WordPress plugin and theme developers as a way to make asynchronous requests in a WordPress site. When a typical AJAX request to admin-ajax.php is made, it loads a few other core WordPress files to make sure the core functions are loaded.

  • /wp-load.php
  • /wp-config.php
  • /wp-settings.php (loads most core files, all active plugins and themes, and the REST API)
  • /wp-admin/includes/admin.php
  • /wp-admin/includes/ajax-actions.php

After loading these files, WordPress calls the admin_init hook, which several core functions hook into. The below core functions are registered on this hook in WordPress 5.9:

  • handle_legacy_widget_preview
  • wp_admin_headers
  • default_password_nag_handler
  • WP_Privacy_Policy_Content::text_change_check
  • WP_Privacy_Policy_Content::add_suggested_content
  • register_setting
  • add_privacy_policy_content
  • send_frame_options_header
  • register_admin_color_schemes
  • _wp_check_for_scheduled_split_terms
  • _wp_check_for_scheduled_update_comment_type
  • _wp_admin_bar_init
  • _maybe_update_core
  • _maybe_update_plugins
  • _maybe_update_themes

After these functions have been called, WordPress finally calls the AJAX action provided in the $_GET[‘action’] or $_POST[‘action’] variable. This triggers a callback function, retrieves the relevant WordPress data, and serves it in the response.

The New Kid on the Block: WP REST API

While relatively new to the WordPress development ecosystem, the WordPress REST API can be used for a number of implementations other than asynchronous requests, from static site generators to headless single-page apps.

A typical REST API request looks slightly different from a request to admin-ajax.php. Since the REST endpoints are handled by the WordPress Rewrite API, the request is passed to /index.php, which then loads the rest of WordPress normally.

  • /index.php
  • /wp-blog-header.php
  • /wp-load.php
  • /wp-config.php
  • /wp-settings.php ( loads most core files, all active plugins and themes, and the REST API)

Unlike requests sent over admin-ajax.php, the REST API doesn’t load the WordPress admin section via /wp-admin/includes/admin.php, nor does it fire the admin_init action hook. Based on that, it would seem that any plugins or themes that don’t rely on admin-specific functionality—but are making asynchronous requests using admin-ajax.php—should see a slight performance boost by switching over to the REST API.

REST API Adoption in the WordPress Ecosystem

Since the inclusion of the REST API in WordPress, it has been largely adopted by WordPress Core, as well as theme and plugin developers.

The most popular usage of the REST API has been in the development of the new WordPress Block Editor. Building custom blocks for the new editor relies heavily on using the REST API through the api-fetch package.

The REST API and the api-fetch package also open up WordPress to a wider variety of use cases. Developers who work with popular frontend JavaScript frameworks can build WordPress themes or great looking plugin interfaces without needing to rely on PHP for templating. Not only that, but it gives WordPress the ability to power single-page applications and mobile apps, something that was not easily possible before.

Finally, it gives WordPress plugin developers a standardized way to work with custom plugin data. For example, WooCommerce has fully integrated with the WordPress REST API. This allows WooCommerce data like products and orders to be created, read, updated, and deleted using the WP REST API request formats and authentication methods. Before this integration, developers would have had to build their own custom endpoints to access this data externally.

The Dark Horse: Must Use Plugin

As with most cases in software development, there are multiple ways to solve a problem. While admin-ajax.php and the REST API are solid choices, building a custom endpoint also has its own advantages. The biggest of these is performance.

There are a few different ways to set up custom endpoints in a WordPress website. The fastest possible endpoint would likely be completely independent of WordPress. It could be as simple as a standalone PHP file that is uploaded to the web server and processes a specific GET request. While fast, it probably wouldn’t be all that helpful, because it won’t have access to any WordPress core functions. Access to these functions often saves a great deal of development time.

A better approach would be to create a custom endpoint in a must-use plugin to process custom asynchronous HTTP requests. That way it can respond to any custom requests after WordPress core loads, but before the plugins and themes are loaded. This would both provide the best performance and prevent conflicts from other plugins that are using the REST API or admin-ajax.php.

Below is a simple example of a must-use plugin that expects a GET or POST variable hfm-ajax, and outputs the value of time() in the response.

If I installed this on the https://hellfish.media site, it could be accessed at https://hellfish.media/?hfm-ajax=1.

Creating the Benchmarks

The must-use plugin functionality is perfect for our benchmark test, so all we need to do is replicate its functionality for admin-ajax.php and the REST API. First, we’ll create the benchmark function, which returns the time value in the response. This makes it easier to see that the requests aren’t being cached.

To register this function for admin-ajax.php, we need to hook the function into a wp_ajax_nopriv_{$action} hook.

We’re using a wp_ajax_nopriv_{$action} hook so that we don’t need to be logged in to test the admin-ajax.php request.

To register this function for the REST API, we hook it into the rest_api_init hook and set up a custom REST API route.

We can put all this code in a custom plugin or the functions.php of a theme or child theme. For the purposes of the benchmark, I’m going to be working on a 1GB/1vCPU Digital Ocean droplet managed by SpinupWP running WordPress 5.9, with no additional plugins, a default theme, and page caching disabled.

Running the Numbers

To perform the actual benchmarking, we’re going to use ApacheBench, a command-line benchmarking tool that allows you to fire off multiple requests at once to get a feel for how the server is performing. To make sure I was testing valid requests, I also verified the output of each URL tested in Postman.

I’ll create an apachebench directory to run the tests and save the output to a file.

Let’s test the admin-ajax.php version first. In the case of the AJAX request, we pass a query string including an action variable with a value of benchmark_request, which matched the $action value of the wp_ajax_nopriv_ hook defined in the test code.

The above command sends 100 GET requests to the /wp-admin/admin-ajax.php file and logs the response times.

With 100 requests, the average response time was 19.86ms. This gives a good baseline for the same test over the REST API, so let’s test that next.

Surprisingly, the REST API is slightly slower in this comparison, with an average response time of 26.14ms over 100 requests. In these tests, the AJAX API is about 27.3% faster than the REST API. The last time I benchmarked the differences, it was around an 18% difference, but the REST API was faster than the AJAX API.

But what about the must-use plugin?

As expected, this is faster than both the AJAX and REST APIs. The average time for the custom request handler is 5.49ms, which is blisteringly fast compared to the other options.

To validate this data, I decided to run the same benchmarks with some content, a few plugins, and a custom theme activated. I used WP Migrate DB Pro to make a copy of our https://hellfish.media demo site, which has some demo content, a custom theme, and a bunch of active plugins, including:

  • Advanced Custom Fields PRO
  • Advanced Forms
  • WP DB Backup
  • EWWW Image Optimizer
  • Simple Custom Post Order
  • WordPress Importer
  • WP Migrate DB Pro
  • WP Offload Media Lite
  • WP Pusher

The average request times are listed below:

  • admin-ajax: 92.4ms
  • REST API: 89.47ms
  • custom request handler: 6.57ms

The first thing you notice is the overall increase in both the admin-ajax.php and REST API request times compared to the must-use plugin. Both admin-ajax.php and REST API requests are around 4x slower, but the must-use plugin is just 1ms slower. The second thing you’ll notice is that admin-ajax.php is now slower on average than the REST API, but only by a few milliseconds.

A website with a different set of plugins, or a different theme, could see a different set of results, but that depends completely on the theme and plugins running on the site, and how they are coded.

How Plugins Affect Asynchronous Request Performance

Every time an admin-ajax.php or REST API request is served by WordPress, most of WordPress core, the active theme, and all the active plugins are loaded. We experienced this firsthand when we developed WP Migrate DB Pro. In early versions, plugins conflicting with migrations made up the majority of our support requests. Some plugins came up so often that we started publishing a list of plugins known to conflict with WP Migrate DB Pro.

This was not an ideal solution, so we developed Compatibility Mode.

WP Migrate DB Pro Compatibility Mode.

Compatibility Mode allows the user to select which plugins to load for requests made by WP Migrate DB Pro. By default, all plugins are prevented from loading. This greatly reduces the chance of another plugin disrupting the migration process.

Compatibility Mode installs a must-use plugin that hooks into the option_active_plugins filter whenever get_option('active_plugins') is called, and executes a function which may modify which plugins are active.

You can make use of the same principle to prevent plugins from loading when running asynchronous requests. Below is an example of a must-use plugin that could be used to exclude specific plugins from an AJAX request.

You have two options if you want to exclude a list of plugins that are loaded for a REST API request. If the REST API endpoint is a WordPress core endpoint, you can check if the REST_REQUEST constant is defined and set to true. This constant is defined in the rest_api_loaded core function. So instead of the DOING_AJAX checks, you could do the following:

If it’s a custom endpoint registered using register_rest_route (the same as we used in our benchmarks), it doesn’t seem possible to use this constant. Instead, we can get the REQUEST_URI variable in the PHP $_SERVER predefined constant, and see if it matches our custom endpoint.

I implemented this code as a must-use plugin and re-ran the benchmarks, first for admin-ajax.php and then for our custom REST API endpoint.

  • admin-ajax: 18.25ms
  • REST API: 28.58ms

Both times are significantly faster than the same benchmarks with all active plugins loaded, and more inline with what we originally saw in the first benchmarks without any active plugins.

Should You Use the WordPress REST API?

In 2016, when the REST API was merged into WordPress core and I created my first comparison benchmarks, there was a slight speed advantage in using the REST API over admin-ajax.php. Today, it seems to be the other way around. As I’m not involved in WordPress core or REST API development, I can’t say why this is the case or what may have changed to cause this. It’s interesting nonetheless.

Creating endpoints for other developers to use is less complicated with the REST API. When we added REST API integration for Advanced Custom Fields, we appreciated that we could leverage the REST standards, schema, and authentication methods, and just register ACF field data on the defined REST API endpoints. The REST API is also better documented than using admin-ajax.php, and therefore more straightforward to implement.

While admin-ajax.php and a custom request handler can require more work to get the data you want to return, they also give you more flexibility in how you format that data. And as we pointed out, a custom request handler is the obvious choice if raw performance is what you’re after.

In terms of reliability, the REST API and admin-ajax.php still depend on the quality and integrity of the active plugins or themes. A poorly coded plugin could still easily interfere with REST API or admin-ajax.php requests, and the likelihood of this increases with the number of plugins installed on your site.

Overall, it’s definitely a good idea to at least consider using the REST API. Adding custom API endpoints is relatively straightforward compared to admin-ajax.php, and it doesn’t take much to switch over existing code either.

Have you converted your admin-ajax requests over to the REST API? Did you see performance increase, decrease, or not change at all? Let us know in the comments below.

Source: https://deliciousbrains.com/comparing-wordpress-rest-api-performance-admin-ajax-php/