1

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 );

1 Answer 1

2

To set is the connected user belongs to the blog, you need to do that on hook wp_login that means the user is connected :

const ROLE_ADMINISTRATOR = "administrator";
const ROLE_CONTRIBUTOR = "contributor";


add_action("wp_login", function ($user_login, \WP_User $user) {


    if (    !is_multisite()
        ||  is_user_member_of_blog()
    ) {
        return;
    }


    $usersAdministrator = get_users([
        "role" => ROLE_ADMINISTRATOR,
    ]);


    if (count($usersAdministrator) > 0) {
        $newRole = ROLE_CONTRIBUTOR;
    } else {
        $newRole = ROLE_ADMINISTRATOR;
    }

    add_user_to_blog(
          get_current_blog_id()
        , $user->ID
        , $newRole
    );


}, 10, 2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.