Skip to main content
Login Join
Snippet · PHP

Control Expiration of Nonce

Shared by Mehul Gohil · May 21, 2026 · @nonce_life

24 views
Back to Snippets

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:

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:

However, globally reducing nonce lifetime can also introduce usability and compatibility issues.

Potential drawbacks:

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:

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;
}