0

I've got as far as successfully filtering the global nonce_life but am running into trouble applying the filter in a specific function in the way described in this answer.

function quote_nonce_lifetime( $day_in_seconds ) {
    return 604800; // 7 days
}
add_filter( 'nonce_life', 'quote_nonce_lifetime' );

The above method works and affects all nonces. However, I only want to extend the nonce lifetime for a specific kind of nonce, something like:

add_filter( 'nonce_life', 'quote_nonce_lifetime' );
$link = wp_nonce_url( get_site_url().'/?quote='.$id, 'view-quote' );
remove_filter( 'nonce_life', 'quote_nonce_lifetime' );

... but it just renders my nonce link already expired. Should this method work or am I barking up the wrong tree?

0

1 Answer 1

0

Not sure if this is the case, but you should know that you need to add the filter both when generating the URL and upon verifying the nonce, i.e. the nonce lifespan needs to match in both cases. Also, you should use add_query_arg() to add query string to an URL..

So if you had this:

add_filter( 'nonce_life', 'quote_nonce_lifetime' );

$id = 123; // just for testing
$link = wp_nonce_url( add_query_arg( 'quote', $id, home_url( '/' ) ), 'view-quote' );

remove_filter( 'nonce_life', 'quote_nonce_lifetime' );

Then upon verifying the nonce, e.g. using wp_verify_nonce(), add the same filter as above:

add_filter( 'nonce_life', 'quote_nonce_lifetime' );

// *In actual implementation, you should check whether the $_GET['_wpnonce'] exists.
if ( wp_verify_nonce( $_GET['_wpnonce'], 'view-quote' ) ) {
    echo 'nonce is valid :)';
} else {
    echo 'nonce has expired!';
}

remove_filter( 'nonce_life', 'quote_nonce_lifetime' );
2
  • 1
    Thanks, @sally-cj – I've only just got around to implementing your suggestion this morning and am happy to say that it appears to have worked. I say "appears" because I've obviously not yet tested a link after seven days but I can tell you that they now validate, which they weren't before, as indicated in my question. Thanks again. Feb 8, 2021 at 13:50
  • I believe it would work, but anyway, if you can, do let me know after the seven days have passed. :)
    – Sally CJ
    Feb 8, 2021 at 17:54

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.