The nonce_life filter in WordPress allows developers to modify how long nonces remain valid before expiring.
In this example, the nonce expiration time is changed from the default WordPress lifetime (approximately 24 hours) to just 120 seconds (2 minutes).
A nonce in WordPress is a security token used to protect actions such as:
- Form submissions
- AJAX requests
- REST API requests
- Admin actions
- Sensitive operations
By shortening the nonce lifetime, the window in which a stolen or leaked nonce can be reused becomes much smaller.
Benefits of shorter nonce lifetimes:
- Reduces replay attack opportunities
- Improves security for sensitive actions
- Useful for temporary privileged operations
- Limits exposure if a nonce is accidentally leaked
- Better suited for one-time or time-sensitive workflows
However, globally reducing nonce lifetime can also introduce usability and compatibility issues.
Potential drawbacks:
- Users may see nonce expiration errors more frequently
- Long-running admin pages may fail
- AJAX-heavy plugins can break unexpectedly
- Editors and administrators may lose work during long sessions
- Third-party plugins may assume default WordPress nonce behavior
Because of this, globally modifying nonce_life is usually not recommended unless the environment is tightly controlled.
A better approach is using different nonce lifetimes for different use cases.
For example:
- 2 minutes for sensitive financial actions
- 10 minutes for temporary approval links
- 1 hour for moderate-security admin tools
- Default WordPress lifetime for normal admin workflows
Instead of changing the nonce lifetime globally, you can temporarily override it only while generating a specific nonce.
<?php
/**
* Reduce WordPress nonce lifetime globally.
*
* WARNING:
* This affects ALL nonces across WordPress including:
* - wp-admin
* - AJAX requests
* - REST API authentication
* - Plugin/theme forms
*
* Default: 24 hours
* New lifespan: 2 minutes
*/
add_filter( 'nonce_life', 'mg_reduce_nonce_lifetime' );
/**
* Set nonce expiration time.
*
* @param int $lifespan Existing nonce lifespan in seconds.
* @return int
*/
function mg_reduce_nonce_lifetime( int $lifespan ): int {
return 120;
}