for a personal plugin (nothing going to the public or commercial), I built an AJAX form and its endpoint is a custom endpoint (REST Api).

When a certain Page containing my form is accessed, I generate a nonce.

Then, the user sends the form, I add the conventional header (X-WP-Nonce) and in the endpoint function I validate the nonce I first created when the page was loaded.

I would like my nonce to be short-lived, that is, 12 hours is too much.

I found I can use apply_filters('nonce_life', timeHere) but I don't know where this line is supposed to be: should it go right before this one?

$nonce = wp_create_nonce('wp_rest');

Moreover: could this line change the lifespan of ANY nonce in my WP or does the change affect only my nonce? I wouldn't want to break other plugins.


1 Answer 1


Yes, using that filter will affect the lifespan of all nonces created after this filter is added, and while it remains in-place. So your best bet is to add it, create the nonce, remove it:

    function my_nonce_lifetime() {
        return 600; // 10 minutes
    add_filter( 'nonce_life', 'my_nonce_lifetime' );
    $nonce = wp_create_nonce( 'wp_rest' );
    remove_filter( 'nonce_life', 'my_nonce_lifetime' );

EDIT: As suggested by someone in the comments, you'll need to use the same filter later on when you're verifying the nonce, as below:

    add_filter( 'nonce_life', 'my_nonce_lifetime' );
    wp_verify_nonce( $your_nonce_value, 'wp_rest' );
    remove_filter( 'nonce_life', 'my_nonce_lifetime' );
  • 2
    Glad it helps! :)
    – Paul G.
    Sep 3, 2017 at 20:45
  • I don't think it works because the nonce_life hook is also used by wp_verify_nonce(): its value must remain constant betweenwp_create_nonce() and wp_verify_nonce().
    – User
    May 4, 2022 at 16:30
  • Did you actually test it?
    – Paul G.
    May 4, 2022 at 21:07
  • Yes, I've tested it :)
    – User
    May 5, 2022 at 8:13
  • Then the solution would be much the same. Wrap the use of wp_verify_nonce() with the same filters and in the same way as you wrap wp_create_nonce()
    – Paul G.
    May 6, 2022 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.