Using WordPress ‘auth_cookie_expiration’ PHP filter

The auth_cookie_expiration WordPress PHP filter allows you to modify the duration of the authentication cookie expiration period.

Usage

add_filter('auth_cookie_expiration', 'your_custom_function', 10, 3);

function your_custom_function($length, $user_id, $remember) {
    // your custom code here
    return $length;
}

Parameters

  • $length: int, duration of the expiration period in seconds.
  • $user_id: int, User ID.
  • $remember: bool, whether to remember the user login (default: false).

More information

See WordPress Developer Resources: auth_cookie_expiration

Examples

To extend the cookie expiration to 30 days:

add_filter('auth_cookie_expiration', 'extend_cookie_expiration', 10, 3);

function extend_cookie_expiration($length, $user_id, $remember) {
    return 30 * DAY_IN_SECONDS;
}

Set different expiration for different user roles

To set different expiration periods for different user roles:

add_filter('auth_cookie_expiration', 'different_expiration_for_roles', 10, 3);

function different_expiration_for_roles($length, $user_id, $remember) {
    $user = get_user_by('id', $user_id);

    if (in_array('administrator', $user->roles)) {
        return 7 * DAY_IN_SECONDS;
    } else {
        return 1 * DAY_IN_SECONDS;
    }
}

Set expiration based on the “remember me” checkbox

To set a longer expiration when the “remember me” checkbox is checked:

add_filter('auth_cookie_expiration', 'remember_me_expiration', 10, 3);

function remember_me_expiration($length, $user_id, $remember) {
    if ($remember) {
        return 30 * DAY_IN_SECONDS;
    } else {
        return 1 * DAY_IN_SECONDS;
    }
}

Set expiration to never expire

To set the cookie expiration to never expire:

add_filter('auth_cookie_expiration', 'never_expire_cookie', 10, 3);

function never_expire_cookie($length, $user_id, $remember) {
    return 50 * YEAR_IN_SECONDS;
}

Set custom expiration for specific users

To set a custom expiration for specific users:

add_filter('auth_cookie_expiration', 'custom_expiration_for_users', 10, 3);

function custom_expiration_for_users($length, $user_id, $remember) {
    $custom_users = array(1, 3, 5); // User IDs for which to set custom expiration

    if (in_array($user_id, $custom_users)) {
        return 14 * DAY_IN_SECONDS;
    } else {
        return $length;
    }
}