Using WordPress ‘check_ajax_referer()’ PHP function

The check_ajax_referer() WordPress PHP function verifies the Ajax request to prevent processing requests external of the blog. It’s a key function for ensuring the security and integrity of your Ajax requests.

Usage

Here’s a generic example of how to use the function:

check_ajax_referer( 'my_action', 'security' );

In this example, 'my_action' is the action nonce, and 'security' is the key to check for the nonce in $_REQUEST.

Parameters

  • $action (int|string) (Optional) – Action nonce. Default is -1.
  • $query_arg (false|string) (Optional) – Key to check for the nonce in $_REQUEST (since 2.5). If false, $_REQUEST values will be evaluated for ‘_ajax_nonce’, and ‘_wpnonce’ (in that order). Default is false.
  • $die (bool) (Optional) – Whether to stop early when the nonce cannot be verified. Default is true.

More information

See WordPress Developer Resources: check_ajax_referer()

This function is a part of the WordPress core and is implemented in version 2.0.3.

Examples

Basic usage

This is a simple usage of check_ajax_referer(). Here the function will check for the nonce in the ‘security’ parameter of the Ajax request.

add_action( 'wp_ajax_my_action', 'my_action_function' );

function my_action_function() {
  check_ajax_referer( 'my_action', 'security' );
  // Your Ajax process here
}

Use with a custom nonce

Here we’ll check for a custom nonce ‘my_custom_nonce’ in the Ajax request.

add_action( 'wp_ajax_my_custom_action', 'my_custom_action_function' );

function my_custom_action_function() {
  check_ajax_referer( 'my_custom_nonce', 'security' );
  // Your Ajax process here
}

Stop early when nonce cannot be verified

In this example, the function will stop the process early when the nonce cannot be verified.

add_action( 'wp_ajax_my_action', 'my_action_function' );

function my_action_function() {
  check_ajax_referer( 'my_action', 'security', true );
  // Your Ajax process here
}

Continue when nonce cannot be verified

Here, the function will continue even when the nonce cannot be verified.

add_action( 'wp_ajax_my_action', 'my_action_function' );

function my_action_function() {
  check_ajax_referer( 'my_action', 'security', false );
  // Your Ajax process here
}

Check for ‘_wpnonce’ in $_REQUEST

In this example, the function will check for ‘_wpnonce’ in $_REQUEST.

add_action( 'wp_ajax_my_action', 'my_action_function' );

function my_action_function() {
  check_ajax_referer( '_wpnonce' );
  // Your Ajax process here
}