Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 68 ยท Forms, Security and Data Handling

Forms and Nonces

Learn to build a safe WordPress form - admin-post.php, wp_nonce_field, wp_verify_nonce, check_admin_referer, nonce lifetime and ticks, their limits and redirect after post.

Any form that changes something on your site, from saving a setting to submitting a comment-like message, invites an attack called cross-site request forgery (CSRF). A malicious page makes the visitor's browser send a request to your site while the visitor is logged in. The request carries the visitor's cookies, so WordPress cannot tell it apart from a real click. WordPress's defense is the nonce: a token that your own page embeds in the form and that an attacker's page cannot guess.

This lesson builds a front-end form that posts to admin-post.php, adds a nonce, verifies it, and ends with a redirect. You will also learn what a nonce is made from, how long it lives, and, just as important, what it does not protect you from.

WordPress cannot run on this site. The WordPress code below is read-only. The runnable examples are plain-PHP stand-ins: the nonce algorithm is a simplified imitation (real WordPress uses its own salts and the user's session token), so the tokens you see here will never match real ones. The ideas, however, match.

What a nonce is

The word means "number used once", but a WordPress nonce is not truly single-use. It is a short hash computed from four things:

  • a time tick (a counter that advances every twelve hours),
  • the action name you chose, such as save_contact,
  • the user ID (0 for visitors), and
  • the user's session token.

WordPress combines them with a secret salt from wp-config.php. Because the action and the user are in the hash, a nonce made for "delete post 5" does not work for "save contact", and a nonce from user A does not work for user B. Because the tick is in the hash, it expires.

A nonce is valid for two ticks, so by default its life is 24 hours. When you verify one, WordPress returns 1 if it was generated in the first twelve hours, 2 if in the second twelve hours, and false if it is invalid or expired. Both 1 and 2 count as success, so always test for truthiness, never for === 1.

sequenceDiagram
    participant U as Visitor browser
    participant P as Your form page
    participant H as admin-post.php
    U->>P: GET the page
    P-->>U: HTML with hidden nonce field
    U->>H: POST action, nonce, fields
    H->>H: wp_verify_nonce(nonce, action)
    H->>H: Sanitize, check capability, save
    H-->>U: 302 redirect to a thank-you URL

The nonce travels out in the page and comes back with the form; a forged request from another site does not have it.

A front-end form with admin-post.php

admin-post.php is the entry point for form submissions that are not AJAX. It works like admin-ajax.php: the form includes a hidden action field, and WordPress fires either admin_post_{action} (logged-in) or admin_post_nopriv_{action} (visitor). Here is the form, as a shortcode callback:

PHP
<?php
// real WordPress, read-only
function myplugin_render_contact_form(): string {
    ob_start();
    ?>
    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
        <input type="hidden" name="action" value="myplugin_contact">
        <?php wp_nonce_field( 'myplugin_contact', 'myplugin_nonce' ); ?>

        <label for="msg">Message</label>
        <textarea id="msg" name="message" required></textarea>

        <button type="submit">Send</button>
    </form>
    <?php
    return (string) ob_get_clean();
}
add_shortcode( 'myplugin_contact', 'myplugin_render_contact_form' );

wp_nonce_field( $action, $name ) prints a hidden input holding the nonce and, by default, a second hidden field _wp_http_referer with the current URL. The second argument names the field; the default is _wpnonce. To put the nonce in a link instead, use wp_nonce_url( $url, $action ), which adds ?_wpnonce=....

The handler

PHP
<?php
add_action( 'admin_post_nopriv_myplugin_contact', 'myplugin_handle_contact' );
add_action( 'admin_post_myplugin_contact', 'myplugin_handle_contact' );

function myplugin_handle_contact(): void {
    if (
        ! isset( $_POST['myplugin_nonce'] )
        || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['myplugin_nonce'] ) ), 'myplugin_contact' )
    ) {
        wp_die( 'Security check failed.', 'Error', [ 'response' => 403 ] );
    }

    $message = isset( $_POST['message'] )
        ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) )
        : '';

    if ( '' === $message ) {
        wp_safe_redirect( add_query_arg( 'sent', 'empty', wp_get_referer() ?: home_url( '/' ) ) );
        exit;
    }

    // ... store or email the message ...

    wp_safe_redirect( add_query_arg( 'sent', '1', wp_get_referer() ?: home_url( '/' ) ) );
    exit;
}

Three habits are visible here. The nonce is read with wp_unslash() and sanitized before use, because everything in $_POST arrives with slashes added by WordPress. The failure path stops with wp_die(). And the success path ends with a redirect and exit, which brings us to the next topic.

Redirect after post

If a handler prints a page directly after a POST, pressing the browser's reload button re-sends the form, and the visitor can submit twice. The standard cure, called post/redirect/get, is to answer with a 302 redirect to a normal GET URL, such as the form page with ?sent=1. The page can then read the flag and show a thank-you message. Use wp_safe_redirect(), which only allows hosts that WordPress trusts, instead of wp_redirect(), and always call exit right afterwards; a redirect function only sets a header, and code below it keeps running.

The shortcuts: check_admin_referer and friends

Inside wp-admin, you rarely call wp_verify_nonce() yourself:

  • check_admin_referer( $action, $query_arg = '_wpnonce' ) verifies the nonce and also checks the referer. On failure it stops with a "The link you followed has expired." page and a 403 status.
  • check_ajax_referer( $action, $query_arg ) is the AJAX twin; it answers -1 with a 403.
  • wp_verify_nonce() returns 1, 2 or false and leaves the decision to you, which is right for front-end handlers where you want a friendly message.

A hand-written settings page also needs this: see admin pages and list tables and meta boxes.

Try it: nonces with ticks, users and actions

This stand-in keeps the same ingredients as WordPress: tick, action, user ID, session token and a secret salt. The tick is ceil( time / 43200 ), where 43200 is the seconds in twelve hours. Verification tests the current tick first, then the one before. We pass the clock in so the output is the same every time.

PHP A nonce generator and verifier with time ticks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the "13 hours later" row. Depending on where the first request sits inside a tick, a nonce can be accepted for anywhere between 12 and 24 hours, so never plan around an exact lifetime. A session change, such as logging out and back in, also invalidates old nonces, because the session token is one of the ingredients.

Try it: the whole admin-post flow

This second stand-in glues the pieces: a dispatcher chooses admin_post_ or admin_post_nopriv_, the handler verifies the nonce, sanitizes the message and answers with a redirect instead of HTML. The stand-in "response" is a status code, a Location value and nothing else.

PHP admin-post flow with nonce check and redirect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The valid submission and the empty one both end with a 302. The browser then makes a plain GET to the thank-you URL, so reloading never re-sends the form.

What nonces are not

Nonces are widely misunderstood, and the official guidance says the same: they are a CSRF defense, not an authentication system.

  • Not authorization. A subscriber can fetch a valid nonce for an admin action by loading a page that prints one. Always add a capability check, such as current_user_can( 'edit_post', $post_id ). See users, roles and capabilities.
  • Not single-use. The same nonce works repeatedly within its lifetime.
  • Not input validation. A valid nonce says the request is genuine, not that the data is safe. Sanitize it, as the next lesson, sanitizing and validating input, shows.
  • Not reliable on cached pages. If a page cache stores HTML that contains a nonce, visitors receive an old token and the form fails after a day. Load the nonce with JavaScript, or exclude the form page from the cache.
  • Weak for visitors. A logged-out visitor has user ID 0 and no session, so all visitors can end up with the same nonce for an action. It still blocks cross-site forgery, but it identifies nobody.

Common mistakes

  • Verifying the wrong action string. The action in wp_nonce_field() and wp_verify_nonce() must match exactly.
  • Testing === 1. The function returns 2 for the older tick.
  • Skipping exit after a redirect. The code below keeps running.
  • Treating the nonce as the only check. Verify capabilities and sanitize input too.
  • Reading $_POST without isset. Missing fields cause notices; guard every access.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which values go into a WordPress nonce?

    Binding the nonce to an action and a user is what stops one token from being reused for something else.
  2. 2. wp_verify_nonce() returns 2. What does that mean?

    Both 1 and 2 mean valid; 2 marks a token from the previous tick. Only false means invalid or expired.
  3. 3. Why should a form handler end with a redirect after saving?

    Post/redirect/get turns the final page into a normal GET, so reload and back do not resend the form.
  4. 4. A logged-in subscriber holds a valid nonce for deleting posts. What stops them from deleting?

    Nonces only prove a request came from your page for that user. Permission needs its own check.
  5. 5. Why can a page cache break a front-end form that has a nonce?

    A cached page freezes the nonce. After its lifetime passes, every submission fails verification.

Summary

  • A nonce defends against CSRF: it is a token built from a time tick, an action, a user ID and a session token.
  • It stays valid for two twelve-hour ticks; wp_verify_nonce() returns 1, 2 or false.
  • Front-end forms post to admin-post.php with a hidden action, handled by admin_post_ or admin_post_nopriv_ hooks.
  • Use wp_nonce_field() in forms, wp_nonce_url() in links, check_admin_referer() in admin screens.
  • Finish with wp_safe_redirect() and exit (post/redirect/get).
  • Nonces are not authorization, not single-use and not input validation: add capability checks and sanitizing.
  • The runnable examples are plain-PHP stand-ins, not WordPress's real nonce code.

Next: Sanitizing and Validating Input