WordPress MU

sync user roles across WordPress Multisite:


<?php

function wpmu_sync_user_roles( $user_id, $role ) {

    // is_multisite() used just as precaution, this code is meant to Multisite only

    if( ! is_multisite() || ! is_main_site() ) {

        return;

    }



    // if( get_current_blog_id() == $id ) {}

    // $blogs = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" ); // get all blogs via sql

    $blogs = get_blogs_of_user( $user_id );

    $original_blog_id = get_current_blog_id();



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



    foreach( $blogs as $blog ) { // iterate through blogs of user

        switch_to_blog( $blog->userblog_id ); // switch to another site



        $site_user = get_user_by( 'id', $user_id );

        $site_user->set_role( $role ); // update role like on main site

    }

    restore_current_blog(); // return to current site

}

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

?>

Sync all roles with capabilities on all sites of the WordPress Multisite Network:


<?php

global $wpdb, $wppa_roles;

if ( is_multisite() && is_super_admin() /*&& $wppa_apply_to_all*/ ) { // sync user roles !!!!!!!!!!!!!!!!!!!!!!!!!!!!

	$blogIds = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );

	$user_capabilities = get_option( $wpdb->prefix.'user_roles');

	foreach( $blogIds as $blog_id ) {

		switch_to_blog( $blog_id );

		$wppa_roles = wppa_getUserRoles();

		$option_name = $wpdb->prefix.'user_roles';

		$result = update_option( $option_name, $user_capabilities );

	}

	restore_current_blog();

	$wppa_roles = wppa_getUserRoles();

}





function wppa_getUserRoles( $wppa_object='role' ) {

	global $wp_roles;



	if( ! isset( $wp_roles ) ) {

		$wp_roles = new WP_Roles();

	}



	if( 'role'===$wppa_object && function_exists( 'bbp_filter_blog_editable_roles' ) ) {  // bbPress plugin is active

		$wppa_roles = bbp_filter_blog_editable_roles( $wp_roles->roles );  // exclude bbPress roles

		$bbp_full_caps = bbp_get_caps_for_role( bbp_get_keymaster_role() );

		// add bbPress keymaster caps to Administrator role

		$wppa_roles['administrator']['capabilities'] = array_merge( $wppa_roles[ 'administrator' ]['capabilities'], $bbp_full_caps );

	}else{

		$wppa_roles = $wp_roles->roles;

	}



	if ( is_array( $wppa_roles ) && count( $wppa_roles ) > 0 ) {

		asort( $wppa_roles );

	}



	return $wppa_roles;

} // end of wppa_getUserRoles()

?>

Leave a Comment