Using WordPress ‘check_admin_referer()’ PHP function

The check_admin_referer() WordPress PHP function is a security measure that ensures a user is referred from another admin page with the right security nonce. Its purpose is to affirm the user’s intent to execute an action, thereby protecting against clickjacking attacks. Although it verifies intent, it does not check the user’s capabilities, which should be done with current_user_can() or similar functions. If the nonce value is incorrect, it will terminate with an “Are You Sure?” message.

Usage

Let’s say you want to verify user intent on an action in your plugin’s options page. First, you would add a nonce to a form using the wp_nonce_field() function:

<form method="post">
  <!-- insert inputs here ... -->
  wp_nonce_field( 'my_action', 'my_nonce_field' );
</form>

In the page where the form is submitted, you can use check_admin_referer() to validate if the form was submitted correctly and update values if the submission was successful:

if ( ! empty( $_POST ) && check_admin_referer( 'my_action', 'my_nonce_field' ) ) {
  // process form data, e.g. update fields
}

Parameters

  • $action (int|string, Optional): The nonce action. Default is -1.
  • $query_arg (string, Optional): The key to check for nonce in $_REQUEST. Default is ‘_wpnonce’.

More information

See WordPress Developer Resources: check_admin_referer()

This function is an important part of the WordPress core and is not deprecated. However, be aware that the script will terminate if the admin referer is not validated.

Examples

Verify Intent to Update User Profile

This example checks if the user intends to update their profile before processing the form data.

if ( ! empty( $_POST ) && check_admin_referer( 'update_profile', 'profile_nonce_field' ) ) {
  // process form data, e.g. update user profile
}

Intent to Change Password

This code snippet verifies user intent to change their password.

if ( ! empty( $_POST ) && check_admin_referer( 'password_change', 'password_nonce_field' ) ) {
  // process form data, e.g. change user password
}

Intent to Delete Post

Before deleting a post, this code ensures the user’s intent.

if ( ! empty( $_POST ) && check_admin_referer( 'delete_post', 'delete_nonce_field' ) ) {
  // process form data, e.g. delete post
}

Intent to Add New Page

This code verifies the user’s intent to add a new page.

if ( ! empty( $_POST ) && check_admin_referer( 'add_new_page', 'page_nonce_field' ) ) {
  // process form data, e.g. add new page
}

Intent to Update Plugin Settings

This example checks the user’s intent to update plugin settings.

if ( ! empty( $_POST ) && check_admin_referer( 'update_plugin', 'plugin_nonce_field' ) ) {
  // process form data, e.g. update plugin settings
}

In each of these cases, if the nonce check fails, the check_admin_referer() function will automatically print a “failed” page and terminate.