A nonce is a one time security token that proves a request came from your own form or link, and not from an attacker who tricked a logged in user. It protects against CSRF attacks. Nonces are valid for a limited time, usually between 12 and 24 hours.

Protect a form

<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
    <?php wp_nonce_field( 'lotgrafix_save_form', 'lotgrafix_nonce' ); ?>
    <input type="hidden" name="action" value="lotgrafix_save_form">
    <input type="text" name="title">
    <button type="submit">Save</button>
</form>

Verify it when the form is submitted

function lotgrafix_save_form() {
    if ( ! isset( $_POST['lotgrafix_nonce'] ) ||
        ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['lotgrafix_nonce'] ) ), 'lotgrafix_save_form' ) ) {
        wp_die( esc_html__( 'Security check failed.', 'lotgrafix' ), '', array( 'response' => 403 ) );
    }

    if ( ! current_user_can( 'edit_posts' ) ) {
        wp_die( esc_html__( 'Not allowed.', 'lotgrafix' ), '', array( 'response' => 403 ) );
    }

    // Safe to process the form here.

    wp_safe_redirect( wp_get_referer() );
    exit;
}
add_action( 'admin_post_lotgrafix_save_form', 'lotgrafix_save_form' );

Protect a link, like a delete button

$lotgrafix_url = wp_nonce_url(
    admin_url( 'admin-post.php?action=lotgrafix_delete&id=5' ),
    'lotgrafix_delete_5'
);

echo '<a href="' . esc_url( $lotgrafix_url ) . '">Delete</a>';
function lotgrafix_delete() {
    check_admin_referer( 'lotgrafix_delete_5' );

    if ( ! current_user_can( 'delete_posts' ) ) {
        wp_die( esc_html__( 'Not allowed.', 'lotgrafix' ), '', array( 'response' => 403 ) );
    }

    // Delete the item here.
}
add_action( 'admin_post_lotgrafix_delete', 'lotgrafix_delete' );

Protect an AJAX request

// Create the nonce and send it to JavaScript.
wp_localize_script( 'lotgrafix-main', 'lotgrafixData', array(
    'nonce' => wp_create_nonce( 'lotgrafix_nonce' ),
) );

// Verify it in the AJAX handler.
check_ajax_referer( 'lotgrafix_nonce', 'nonce' );

Main functions

  • wp_nonce_field(): prints hidden fields in a form.
  • wp_create_nonce(): creates a nonce string.
  • wp_verify_nonce(): returns false if the nonce is invalid or expired.
  • check_admin_referer() and check_ajax_referer(): verify and stop the request on failure.
  • wp_nonce_url(): adds a nonce to a URL.

Remember

A nonce is not a replacement for permission checks. Always verify the nonce and also check what the user is allowed to do with current_user_can().

«
»