Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How to synchronize roles on all sites of the Multisite Network if roles were changed on main site?

share|improve this question

1 Answer 1

There's an action hook in the set_role function.

It's a matter of detecting if this is happening in the main site, and, if it does, get all blogs of the user and change all roles. More details in code comments.

add_action( 'set_user_role', 'sync_user_roles_wpse_91745', 10, 2 );

function sync_user_roles_wpse_91745( $user_id, $role )
{
    // is_multisite() used just as precaution, this code is meant to Multisite only
    if( !is_multisite() || !is_main_site() )
        return;

    // Initial data
    $blogs = get_blogs_of_user( $user_id );
    $original_blog_id = get_current_blog_id();

    // Remove main site from affected sites
    unset( $blogs[ $original_blog_id ] );

    // Iterate through blogs of user
    foreach ( $blogs as $blog ) 
    {
        // Work with another site
        switch_to_blog( $blog->userblog_id );

        // Grab all user info and update role as in main site
        $site_user = get_user_by( 'id', $user_id );
        $site_user->set_role( $role );
    }

    // Back to original main site
    switch_to_blog( $original_blog_id );    
}

I didn't know that, but the user ID remains the same across the network, in the tables wp_users and wp_{$site_id}_users.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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