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.



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' );
  • 2
    Glad it helps! :) – Paul G. Sep 3 '17 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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