auth_cookie_expiration
This filter is documented in wp-includes/pluggable.php */ Filters the expiration time for authentication cookies when a user logs in.
add_filter( 'auth_cookie_expiration', $callback, 10, 1 );
Description
Filters the duration of the authentication cookie. Developers can use this hook to dynamically set how long a user remains logged in, offering more flexibility than the static default.
Usage
add_filter( 'auth_cookie_expiration', 'your_function_name', 10, 1 );
Return Value
The filtered value.
Examples
/**
* Extend the default authentication cookie expiration for administrators.
*
* This function hooks into the 'auth_cookie_expiration' filter to increase
* the default expiration time for authentication cookies, specifically for
* users with the 'administrator' role. This is intended to provide a
* longer "remember me" experience for administrators.
*
* @param int $expiration The current expiration time in seconds.
* @param int $user_id The ID of the user for whom the cookie is being set.
* @param bool $is_logged_in Whether the user is currently logged in.
* @return int The modified expiration time in seconds.
*/
function my_custom_auth_cookie_expiration( $expiration, $user_id, $is_logged_in ) {
// Check if the current user is an administrator.
if ( $user_id && user_can( $user_id, 'manage_options' ) ) {
// If the user is an administrator, extend the cookie expiration to 30 days (2592000 seconds).
// The original default is 172800 seconds (2 days).
return 2592000;
}
// For all other users, return the original expiration time.
return $expiration;
}
add_filter( 'auth_cookie_expiration', 'my_custom_auth_cookie_expiration', 10, 3 );
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/includes/user-switching.php:150
public static function remember() {
/** This filter is documented in wp-includes/pluggable.php */
$cookie_life = apply_filters( 'auth_cookie_expiration', 172800, get_current_user_id(), false );
$current = wp_parse_auth_cookie( '', 'logged_in' );
if ( ! $current ) {
return false;
}
// Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
// If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
return ( intval( $current['expiration'] ) - time() > $cookie_life );
}