简体   繁体   中英

Using auth_cookie_expiration in wordpress to time out cookie but not for administrator

I wonder if you could help me with something. The following piece of code works in that after 30 seconds of logging in (yes its just for testing) users are logged out, but the administrator isn't.

function logout_after_time( $expiration, $user_id) {
    if(!user_can($user_id, 'update_plugins') ){
        $expiration = 30; // yes this is 30 seconds for testing
    }
    return $expiration;
}
add_filter('auth_cookie_expiration','logout_after_time', 10, 2);

However if I change that to the following:

function logout_after_time( $expiration, $user_id) {
        if(!current_user_can($user_id, 'administrator') ){
            $expiration = 30; // yes this is 30 seconds for testing
        }
        return $expiration;
    }
    add_filter('auth_cookie_expiration','logout_after_time', 10, 2);

It logs out all users. I can't for the life of me think why this is? Ideally I don't really want to check for caps, I would like to check for a role.

Any ideas what I am doing wrong? Thanks for all those who can help:)

Using current_user_can should not be used to check for roles, see the documentation :

Passing role names to current_user_can() is discouraged as this is not guaranteed to work correctly (see #22624)

What you can do to check for a role though, is see if one role is in the array of roles of the current user:

$currentUser = wp_get_current_user();
if ( !in_array( 'administrator', (array) $user->roles ) ) {
    // Do something for users that don't have to role ' administrator'. 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM