Assign role to user on first login, if they are first (after admin)

by setrole   Last Updated August 06, 2018 09:08 AM

I'm running a Wordpress Multisite.

I want the first user to log into a new site to be assigned the Administrator role, so they can administer the other roles. The second user, and all users thereafter on that particular site, should just be Contributors.

When I create a new site, the first user to log in there should also have the Administrator role, and all other after Contributors. How can I do this?

I tried to use both wpmu_new_user and wpmu_activate_user with the following function, which isn't working, and the created user has no role when I try to set it with this function:

function test_onboarding_user($user_id){

    $user = get_user_by( 'id', $user_id );
    if (!$user->exists()) {
        return;
    }
    $current_user_list = get_users();
    if(count($current_user_list) == 2){ // The first user is the Super Admin, so this user should be #2
        $user->set_role('administrator');
    } else {
        $user->set_role('contributor');
    }
}

add_action( 'wpmu_new_user', 'test_onboarding_user', 20, 1 );


Related Questions