Keep users logged in for longer by extending cookie expiration time

Code snippets should be placed in your functions.php file or extracted in to your own custom plugin.

WordPress keeps users logged in by saving a cookie with an expiration time. To keep users logged in for a longer (or shorter) period of time, we can hook into auth_cookie_expiration.

add_filter('auth_cookie_expiration', 'wptd_logged_in_expiration');
function wptd_logged_in_expiration($expire_in, $user_id, $remember){
	return 31556952; // 1 year in seconds
}

Time in seconds:

1 year31556952
6 months15778476
1 month2629746
1 week606864
1 day86400

In the code above, you can see there are 3 parameters: $expire_in, $user_id and $remember. We can use these values to get creative with setting cookies for different users.

For example, $remember is a boolean value, so we’re able to check if the user asked to be remembered, and give them a longer logged-in session by returning different values:

add_filter('auth_cookie_expiration', 'wptd_logged_in_expiration', 10, 3);
function wptd_logged_in_expiration($expire_in, $user_id, $remember) {
	if($remember) {
		return 31556952; // 1 year in seconds
	} else {
		return 86400; // 1 day in seconds
	}
}

Another option would be to use the $user_id to check the role of the user. Administrators could be logged in for months but other roles would be logged in for just a week.

@wpthemedotdev Post