Home > Net >  How can I exclude a user role from being changed when logging in?
How can I exclude a user role from being changed when logging in?

Time:03-23

I am trying to modify a code snippet I have been using for some time on my WordPress site. Previously, when a user with the default 'Subscriber' role logged in, the role would be changed to 'Directory User'. I had excluded the 'Administrator' role from being changed. I want to keep this behavior but I have added a new user role, 'Directory Contributor' that I don't want to be changed either. I have come up with the following code, but the 'Directory Contributor' role is being changed to 'Directory User'. How can I modify my code so that this does not occur?

    function uiwc_change_role()
{
    // get WP_user object
    $user = wp_get_current_user();
    $role = $user->roles;
    
    // if the this is a registered user and this user is not an admin or directory contributor
    if (is_user_logged_in() && !user_can($user, 'administrator', 'directory_contributor') && !in_array('directory_user', $role)) {

        //set the new role to directory user
        $user->set_role('directory_user');
    }
}
add_action('wp_footer', 'uiwc_change_role');

CodePudding user response:

You want to use array_intersect since $role is an array. user_can checks for capabilities, and not user roles, so it's probably best to leave it out of the picture here.

It also seems more sensible to hook to init unless you have some other reason not to.

function uiwc_change_role() {
    // get WP_user object.
    $user = wp_get_current_user();
    $role = $user->roles;
    // if the user is a registered user and this user is not an admin or directory contributor.
    if ( is_user_logged_in() && ! array_intersect( array( 'administrator', 'directory_contributor' ), $role ) ) {
        // set the new role to directory user.
        $user->set_role( 'directory_user' );
    }
}
add_action( 'init', 'uiwc_change_role' );
  • Related