The check_ajax_referer WordPress PHP action fires once the Ajax request has been validated or not. It is used for the Ajax nonce action.
Usage
add_action('check_ajax_referer', 'your_custom_function', 10, 2); function your_custom_function($action, $result) { // your custom code here return $action; }
Parameters
$action
(string) – The Ajax nonce action.$result
(false|int) – False if the nonce is invalid, 1 if the nonce is valid and generated between 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
More information
See WordPress Developer Resources: check_ajax_referer
Examples
Log Invalid Ajax Nonce
Log invalid Ajax nonce attempts to a debug file.
add_action('check_ajax_referer', 'log_invalid_ajax_nonce', 10, 2); function log_invalid_ajax_nonce($action, $result) { if (false === $result) { error_log("Invalid nonce for action: {$action}"); } return $action; }
Perform an Action if Nonce is Valid
Perform a custom action if the Ajax nonce is valid.
add_action('check_ajax_referer', 'perform_custom_action', 10, 2); function perform_custom_action($action, $result) { if (1 === $result || 2 === $result) { // Perform your custom action } return $action; }
Modify the Ajax Nonce Action
Modify the Ajax nonce action based on the $result
.
add_action('check_ajax_referer', 'modify_ajax_nonce_action', 10, 2); function modify_ajax_nonce_action($action, $result) { if (false === $result) { $action = 'custom_invalid_action'; } return $action; }
Block Old Nonces
Block Ajax requests with nonces older than 12 hours.
add_action('check_ajax_referer', 'block_old_nonces', 10, 2); function block_old_nonces($action, $result) { if (2 === $result) { wp_die('Nonce is too old, please refresh the page and try again.'); } return $action; }
Redirect on Invalid Nonce
Redirect users to a custom page when the Ajax nonce is invalid.
add_action('check_ajax_referer', 'redirect_invalid_nonce', 10, 2); function redirect_invalid_nonce($action, $result) { if (false === $result) { wp_redirect(home_url('/custom-page/')); exit; } return $action; }