admin-ajax.php or the REST API: which one for AJAX in WordPress
WordPress has two ways to answer requests from JavaScript. admin-ajax.php exists since WordPress 2.1: every request goes to one file with an action parameter. The REST API (in core since 4.7) has its own URL per resource, HTTP methods, argument validation and JSON responses. Both work; for new code the REST API is usually the better choice.
Problem: A front-end component must load posts of a selected category and save a preference of the logged-in user, and you have to decide between admin-ajax.php and the REST API.
Solution: Use a REST route for both: a GET route with 'permission_callback' => '__return_true' and validated arguments for the public list, a POST route with a capability check for saving. Keep admin-ajax.php for existing code and for plugins that must support very old WordPress versions.
The same request with admin-ajax.php
<?php
add_action( 'wp_ajax_ha_posts', 'ha_ajax_posts' );
add_action( 'wp_ajax_nopriv_ha_posts', 'ha_ajax_posts' );
function ha_ajax_posts() {
$term_id = isset( $_GET['term_id'] ) ? absint( $_GET['term_id'] ) : 0;
wp_send_json_success( ha_get_posts_data( $term_id ) );
}
function ha_get_posts_data( $term_id ) {
$posts = get_posts( array(
'posts_per_page' => 10,
'cat' => $term_id,
'no_found_rows' => true,
) );
return array_map( function ( $p ) {
return array( 'id' => $p->ID, 'title' => get_the_title( $p ), 'url' => get_permalink( $p ) );
}, $posts );
}
Everything is in your hands: reading and validating parameters, the response format, the status codes. The details of this approach are in handling AJAX requests with wp_ajax.
The REST version
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'ha/v1', '/posts', array(
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
return ha_get_posts_data( $request['term_id'] );
},
'permission_callback' => '__return_true', // public data
'args' => array(
'term_id' => array( 'type' => 'integer', 'required' => true, 'minimum' => 1 ),
),
) );
register_rest_route( 'ha/v1', '/preferences', array(
'methods' => 'POST',
'callback' => function ( WP_REST_Request $request ) {
update_user_meta( get_current_user_id(), 'ha_view_mode', $request['view_mode'] );
return array( 'saved' => true );
},
'permission_callback' => function () {
return is_user_logged_in();
},
'args' => array(
'view_mode' => array( 'type' => 'string', 'enum' => array( 'grid', 'list' ), 'required' => true ),
),
) );
} );
The arguments are checked against their schema before the callback runs: a missing or wrong term_id gets a 400 response with an explanation, without any code from you.
fetch( '/wp-json/ha/v1/preferences', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': haSettings.nonce },
body: JSON.stringify( { view_mode: 'list' } )
} );
The nonce comes from PHP with wp_create_nonce( 'wp_rest' ), passed via wp_localize_script().
The differences that matter
- Logged-in users. Both use the login cookie, and both need a nonce against requests from other sites. In the REST API the nonce goes into the
X-WP-Nonceheader; without it the request runs as a guest. - Speed. Both load WordPress completely. admin-ajax.php also loads the admin code, so a REST request is usually a little faster.
- Caching. Public GET requests to the REST API have normal URLs and can be cached by a page cache or a CDN if you configure it; admin-ajax.php requests normally bypass caches.
- Discoverability. REST routes are listed at /wp-json/, with their arguments. Do not put anything into a public route that should stay hidden.
NOTE: Some security plugins disable the REST API for guests. Then public REST routes return 401 for visitors, and the front-end feature breaks. Test the feature in a private window, and if you ship a plugin, mention that it needs the REST API, or fall back to admin-ajax.php.