How to Handle AJAX Requests in WordPress with wp_ajax

Handle AJAX requests in WordPress with wp_ajax

WordPress has its own AJAX entry point: every request goes to wp-admin/admin-ajax.php with an action parameter, and WordPress calls the PHP function registered for that action. All of WordPress is loaded, so in the handler you can use any function, check the user and work with the database.

Problem: A theme needs to load or save data without reloading the page, safely and for both logged-in users and guests.

Solution: Register the handler on wp_ajax_{action} (logged-in users) and wp_ajax_nopriv_{action} (guests), pass the URL and a nonce to the script with wp_localize_script(), check the nonce with check_ajax_referer() and answer with wp_send_json_success() or wp_send_json_error().

The PHP handler

The example counts post views:

<?php
add_action( 'wp_ajax_ha_post_views', 'ha_ajax_post_views' );        // logged-in users
add_action( 'wp_ajax_nopriv_ha_post_views', 'ha_ajax_post_views' ); // guests

function ha_ajax_post_views() {
    check_ajax_referer( 'ha_post_views', '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( array( 'message' => 'Invalid post.' ), 400 );
    }

    $views = (int) get_post_meta( $post_id, '_ha_views', true ) + 1;
    update_post_meta( $post_id, '_ha_views', $views );

    wp_send_json_success( array( 'views' => $views ) );
}

Without the nopriv line, guests get the answer 0: WordPress found no handler for them.

Passing the URL and the nonce

The ajaxurl variable exists only in the admin, on the front end the script gets the URL from PHP, together with the nonce and the ID of the current post:

<?php
add_action( 'wp_enqueue_scripts', function () {
    if ( ! is_single() ) {
        return;
    }

    wp_enqueue_script( 'ha-views', get_stylesheet_directory_uri() . '/js/views.js', array( 'jquery' ), '1.0', true );

    wp_localize_script( 'ha-views', 'haViews', array(
        'url'    => admin_url( 'admin-ajax.php' ),
        'nonce'  => wp_create_nonce( 'ha_post_views' ),
        'postId' => get_the_ID(),
    ) );
} );

The JavaScript

jQuery( function ( $ ) {
    $.post( haViews.url, {
        action:  'ha_post_views',
        nonce:   haViews.nonce,
        post_id: haViews.postId
    } ).done( function ( response ) {
        if ( response.success ) {
            $( '.view-count' ).text( response.data.views );
        }
    } );
} );

A bigger example with a search field that shows results while typing is in AJAX live search in WordPress.

NOTE: A nonce protects against requests sent from other sites on behalf of a logged-in user, but it is not a permission check. For actions that change something important, also check current_user_can() in the handler. And remember that page caching stores the nonce in the HTML: after 12–24 hours a cached page has an expired nonce and the request fails. For a harmless guest action like this counter on a cached site, either skip the nonce check for guests or keep the cache lifetime shorter than the nonce lifetime.