Preferred method of setting user role only works on Main Site in Network

I'm working on a multisite installation and I have this function to hook to a WordPress action.

The objective is to 'add' user roles to users on the sub-sites as the same user's role changes on the main site.

This function - using wp_update_user - changes the desired user's role at sub-sites to the new role and removes other roles they have, but leaves the role on the main site as is:

function updateRole_onSubSites( $therole ){
$user_id = wp_get_current_user()-ID;
foreach ( get_sites() as $site ) {
    switch_to_blog( $site-blog_id );
        if ( !current_user_can('update_core')  !is_main_site() ){
            $updateUser = wp_update_user(array(
                'ID' = $user_id,
                'role' = $therole
            ));
        }
    restore_current_blog();
}
}

What I need is to add roles to the existing role on the sub-site. So I tried the code below - using add_role - which adds roles to the user only on the main site but does absolutely nothing on sub-sites, whereas it should be the other way round:

function updateRole_onSubSites( $therole ){
$user_id = wp_get_current_user()-ID;
$theuser = new WP_User( $user_id );

foreach ( get_sites() as $site ){
    switch_to_blog( $site-blog_id );
        if ( !current_user_can('update_core')  !is_main_site() ){

            $theuser-add_role( $therole );

        }
    restore_current_blog();
}
}

Help please! Thank you.

Okay, so I finally discovered a simple solution, I only had to move the $user_id and $theuser variables to after the switch_to_blog function:

function updateRole_onSubSites( $therole ){
    foreach ( get_sites() as $site ) {
        switch_to_blog( $site-blog_id );
            if ( !current_user_can('update_core')  !is_main_site() ){
                $user_id = wp_get_current_user()-ID;
                $theuser = new WP_User( $user_id );

                    $theuser-add_role( $therole );
            }
        restore_current_blog();
    }
}

Now it works perfectly as intended.

Topic multisite-user-management multisite Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.