Question

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?

Was it helpful?

Solution

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' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top