Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 68 ยท REST API, AJAX and Blocks

AJAX in WordPress

Learn how WordPress AJAX works - admin-ajax.php actions, wp_ajax_ and wp_ajax_nopriv_ hooks, nonces, wp_send_json, localized script data, and when to use the REST API instead.

Sooner or later a page needs to talk to the server without reloading: a "like" button, a live search box, a "load more" link. WordPress has had a built-in answer for this since long before the REST API existed: a single file called admin-ajax.php. Your JavaScript sends a request to that file with an action name, WordPress fires a hook with that name, and your PHP callback answers with JSON.

This lesson explains how that old route works, how nonces protect it, how to hand the URL and the nonce to your script, and why new code often reaches for a custom REST endpoint instead. You will not need to choose blindly afterwards: there is a short checklist at the end.

WordPress cannot run on this site. The real WordPress code below is read-only. The runnable examples are plain-PHP stand-ins that copy the shape of the system (an action dispatcher, a nonce check, JSON envelopes). They are not WordPress's own code, and the nonce stand-in is deliberately simpler than the real one.

How admin-ajax.php works

Every AJAX request goes to the same URL, /wp-admin/admin-ajax.php, even for visitors who are not logged in (the file lives in wp-admin, but it is meant for the front end too). The request carries a field called action. WordPress loads itself, then fires one of two hooks:

  • wp_ajax_{action} when the visitor is logged in.
  • wp_ajax_nopriv_{action} when the visitor is logged out.

If nobody registered a callback for the hook that applies, WordPress ends the request with the text 0 and a 400 status. That is the famous "ajax returns 0" problem. It almost always means your action name is misspelled, or you only registered the logged-in hook and then tested while logged out.

sequenceDiagram
    participant B as Browser
    participant A as admin-ajax.php
    participant H as Your callback
    B->>A: POST action=save_like, nonce, post_id
    A->>A: Load WordPress, find the user
    A->>H: do_action wp_ajax_save_like (or nopriv)
    H->>H: Check nonce and capability
    H-->>B: wp_send_json_success(data)

One entry file, one hook per action name, and your callback does the real work, including the security checks.

Registering an action

Here is a complete handler for a "like" button. Notice the three jobs your callback must do: verify the nonce, validate and sanitize input, and send a JSON answer.

PHP
<?php
// In your plugin or theme's functions.php (real WordPress, read-only)
add_action( 'wp_ajax_myplugin_like', 'myplugin_handle_like' );
add_action( 'wp_ajax_nopriv_myplugin_like', 'myplugin_handle_like' );

function myplugin_handle_like(): void {
    check_ajax_referer( 'myplugin_like', 'nonce' );

    $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;

    if ( ! $post_id || 'publish' !== get_post_status( $post_id ) ) {
        wp_send_json_error( [ 'message' => 'Unknown post.' ], 404 );
    }

    $likes = (int) get_post_meta( $post_id, 'myplugin_likes', true ) + 1;
    update_post_meta( $post_id, 'myplugin_likes', $likes );

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

Registering the same function on both hooks means "anyone can like". If an action should be for logged-in users only, register only wp_ajax_... and check a capability inside with current_user_can(). Never rely on the missing nopriv hook alone as your security: a handler also needs its own checks, as the lesson on capabilities and roles explains.

The helpers that end the request

wp_send_json_success( $data ) and wp_send_json_error( $data, $status ) print JSON in a fixed envelope and then stop PHP with wp_die():

JSON
{ "success": true,  "data": { "likes": 7 } }
{ "success": false, "data": { "message": "Unknown post." } }

Because they end the request, any code after them never runs. The older pattern of echoing json_encode() and then calling die() still works, but the helpers also set the right Content-Type header, so prefer them. For a custom shape, wp_send_json( $array ) sends exactly what you pass.

Nonces: proving the request came from your page

An AJAX action changes data, so it needs protection against forged requests. The tool WordPress gives you is the nonce, a short token tied to an action name, to the current user and to a time window. You create it in PHP, hand it to the script, send it back in the request and verify it in the callback with check_ajax_referer(). If the nonce is missing or wrong, WordPress answers -1 with a 403 status. The lesson on forms and nonces covers their lifetime and limits.

A nonce is not a login check and not a capability check. It proves "this request was built by a page WordPress rendered for this user", nothing more.

Giving your script the URL and the nonce

The script needs two values it cannot know by itself: the AJAX URL and a fresh nonce. Pass them when you enqueue the script, using wp_localize_script() (which creates a JavaScript object) or the newer wp_add_inline_script() with wp_json_encode():

PHP
<?php
add_action( 'wp_enqueue_scripts', function (): void {
    wp_enqueue_script(
        'myplugin-like',
        plugins_url( 'js/like.js', __FILE__ ),
        [],
        '1.0.0',
        [ 'in_footer' => true ]
    );

    wp_localize_script( 'myplugin-like', 'mypluginLike', [
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'myplugin_like' ),
    ] );
} );

That prints an inline script before yours, roughly var mypluginLike = {"ajaxUrl":"...","nonce":"..."};. Your file can then read mypluginLike.nonce. See enqueuing styles and scripts for the handles and dependencies behind this call.

The browser side uses plain fetch(). The body is form-encoded because admin-ajax.php reads $_POST:

JavaScript
// like.js (read-only)
async function like( postId ) {
    const body = new URLSearchParams( {
        action: 'myplugin_like',
        nonce: mypluginLike.nonce,
        post_id: String( postId ),
    } );

    const response = await fetch( mypluginLike.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        body,
    } );

    const result = await response.json();
    if ( ! result.success ) {
        throw new Error( result.data.message );
    }
    return result.data.likes;
}

Try it: a mini action dispatcher

This stand-in registers handlers under wp_ajax_ and wp_ajax_nopriv_ names, picks the hook from the login state, and checks a nonce built from the user, the action and a time tick (a number that grows every twelve hours in real WordPress; here we just pass it in). Read how the three failure cases differ.

PHP A mini admin-ajax dispatcher with a nonce check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The visitor with a nonce made for user 5 fails: the user ID is part of what a nonce is built from, so a token cannot be borrowed by someone else.

Try it: JSON envelopes and localized data

Two small stand-ins you will meet constantly: the {success, data} envelope that wp_send_json_* prints, and the inline script line that wp_localize_script() produces.

PHP wp_send_json and wp_localize_script stand-ins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real wp_localize_script() also turns scalar values into strings, which is a known quirk: a number you pass arrives in JavaScript as a string. Cast it in your script, or use wp_add_inline_script() with wp_json_encode() to keep real types.

admin-ajax or REST: which should you use?

Question admin-ajax.php REST API
Loads all of WordPress per call Yes, plus all active plugins Yes, but it is built around routes and verbs
Clear URLs and HTTP verbs No, one URL, action field Yes, GET /wp-json/myplugin/v1/likes/7
Input validation built in No, you write it Yes, args with validate and sanitize callbacks
Permission model Your own checks permission_callback is required
Works for third-party clients Awkward Designed for it
Caching of GET requests Hard Easier, because the URL is meaningful

For new features, prefer the REST API. It gives you structured routes, validation and a required permission check. Keep admin-ajax.php for old code you maintain, for quick admin-side helpers, and for plugins that must work on very old WordPress versions. Whichever you choose, the rules stay the same: check permissions, validate input, escape output, and verify a nonce for cookie-authenticated requests. The REST version of the like button uses wp_create_nonce( 'wp_rest' ) sent as an X-WP-Nonce header, as described in the REST API lesson.

Common mistakes

  • Getting 0 back. Wrong action name, or only one of the two hooks registered for the audience you are testing.
  • Forgetting to end the request. If you echo output and do not call wp_die() or a wp_send_json_* helper, WordPress may append a stray 0 to your response.
  • Skipping the capability check. A nonce is not authorization. A logged-in subscriber also has a valid nonce.
  • Trusting $_POST. Read it through the sanitizers in sanitizing and validating input.
  • Hardcoding the URL. Always use admin_url( 'admin-ajax.php' ); sites can live in subdirectories.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A logged-out visitor sends action=save_note, but you only registered wp_ajax_save_note. What does WordPress return?

    Logged-out requests fire the wp_ajax_nopriv_ hook. With nothing registered there, WordPress ends the request with 0.
  2. 2. What does check_ajax_referer() protect against?

    A nonce ties a request to an action, a user and a time window. It is a CSRF defense, not an authorization check or an input filter.
  3. 3. How does a front-end script usually learn the AJAX URL and a fresh nonce?

    PHP creates the nonce and knows the right URL, so it prints them in an inline script next to your script handle.
  4. 4. Which is a good reason to choose a REST route over admin-ajax.php for a new feature?

    Structure, validation and a mandatory permission callback make REST the better default for new code.

Summary

  • admin-ajax.php receives an action and fires wp_ajax_{action} for logged-in users or wp_ajax_nopriv_{action} for visitors; no callback means 0.
  • Callbacks must verify a nonce, check capabilities where needed, sanitize input and end with wp_send_json_success() or wp_send_json_error().
  • A nonce proves the request came from your page for that user; it does not prove permission.
  • Pass the AJAX URL and nonce to your script with wp_localize_script() or an inline script.
  • For new work, prefer a REST route; keep admin-ajax for legacy code and simple admin helpers.
  • The runnable examples are plain-PHP stand-ins, not the real WordPress code.

Next: Building Blocks: An Overview