Using WordPress ‘nonce_life’ PHP filter

The nonce_life WordPress PHP filter allows you to modify the lifespan of nonces in seconds. The default value is 86,400 seconds, or one day.

Usage

add_filter( 'nonce_life', 'custom_nonce_life', 10, 2 );
function custom_nonce_life( $lifespan, $action ) {
    // your custom code here
    return $lifespan;
}

Parameters

  • $lifespan (int): Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
  • $action (string|int): The nonce action, or -1 if none was provided.

More information

See WordPress Developer Resources: nonce_life

Examples

Extend nonce lifespan to 48 hours

Extend the lifespan of nonces to 48 hours (172,800 seconds).

add_filter( 'nonce_life', 'extend_nonce_life' );
function extend_nonce_life( $lifespan ) {
    return 172800;
}

Shorten nonce lifespan to 1 hour

Shorten the lifespan of nonces to 1 hour (3,600 seconds).

add_filter( 'nonce_life', 'shorten_nonce_life' );
function shorten_nonce_life( $lifespan ) {
    return 3600;
}

Different nonce lifespan for specific action

Set a different nonce lifespan for a specific action, such as ‘custom_action’.

add_filter( 'nonce_life', 'custom_action_nonce_life', 10, 2 );
function custom_action_nonce_life( $lifespan, $action ) {
    if ( 'custom_action' === $action ) {
        return 7200; // 2 hours
    }
    return $lifespan;
}

Extend nonce lifespan for logged-in users

Extend the lifespan of nonces to 7 days (604,800 seconds) for logged-in users.

add_filter( 'nonce_life', 'extend_logged_in_nonce_life' );
function extend_logged_in_nonce_life( $lifespan ) {
    if ( is_user_logged_in() ) {
        return 604800;
    }
    return $lifespan;
}

Shorten nonce lifespan for specific IP address

Shorten the lifespan of nonces to 30 minutes (1,800 seconds) for a specific IP address.

add_filter( 'nonce_life', 'shorten_ip_nonce_life' );
function shorten_ip_nonce_life( $lifespan ) {
    if ( '123.123.123.123' === $_SERVER['REMOTE_ADDR'] ) {
        return 1800;
    }
    return $lifespan;
}