Using WordPress ‘check_admin_referer’ PHP action

The check_admin_referer WordPress PHP action fires once the admin request has been validated or not, based on the nonce action.

Usage

add_action('check_admin_referer', 'your_custom_function', 10, 2);

function your_custom_function($action, $result) {
    // your custom code here
    return $action;
}

Parameters

  • $action (string) – The 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_admin_referer

Examples

Log Invalid Nonces

Log invalid nonce attempts for debugging purposes.

add_action('check_admin_referer', 'log_invalid_nonce', 10, 2);

function log_invalid_nonce($action, $result) {
    if (!$result) {
        error_log("Invalid nonce for action: $action");
    }
    return $action;
}

Custom Security Check

Add an additional security check based on user role.

add_action('check_admin_referer', 'custom_security_check', 10, 2);

function custom_security_check($action, $result) {
    if ($result && current_user_can('editor')) {
        // Perform custom security check here
    }
    return $action;
}

Redirect Invalid Nonces

Redirect users to a specific page when the nonce is invalid.

add_action('check_admin_referer', 'redirect_invalid_nonce', 10, 2);

function redirect_invalid_nonce($action, $result) {
    if (!$result) {
        wp_redirect('https://example.com/error-page/');
        exit;
    }
    return $action;
}

Perform Custom Action on Valid Nonces

Perform a custom action when the nonce is valid.

add_action('check_admin_referer', 'custom_action_on_valid_nonce', 10, 2);

function custom_action_on_valid_nonce($action, $result) {
    if ($result) {
        // Perform custom action here
    }
    return $action;
}

Notify Admin on Invalid Nonces

Send an email notification to the admin when a nonce is invalid.

add_action('check_admin_referer', 'notify_admin_invalid_nonce', 10, 2);

function notify_admin_invalid_nonce($action, $result) {
    if (!$result) {
        $admin_email = get_option('admin_email');
        $subject = "Invalid Nonce Detected";
        $message = "An invalid nonce for action '$action' was detected.";
        wp_mail($admin_email, $subject, $message);
    }
    return $action;
}