Replace User Role on all Sites in Muiltisite

Mods and Stuff for WordPress
Post Reply
User avatar
syntax
Site Admin
Posts: 54
Joined: Tue Jan 06, 2009 9:25 pm

Replace User Role on all Sites in Muiltisite

Post by syntax » Tue Feb 16, 2016 9:28 pm

I couldn't find a plugin to do this so I wrote this function. Place it in a plugin file. Can probably put it in a theme too, not sure if you'd remove the init action hook in that case and just run the function directly.

Code: Select all

function asd_change_user_role_sitewide($user, $role) {
	global $wpdb;
	
	if ( is_multisite() ) {
		$current_blog = $wpdb->blogid;
		
		$blog_ids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );
		foreach ( $blog_ids as $blog_id ) {
			switch_to_blog( $blog_id );
			
			$roles = new WP_Roles();
			$roles_names = $roles->get_names();
			$wp_user = get_user_by('login', $user);
			
			if (!empty($roles_names[$role]) && !empty($wp_user)) {
				foreach ($roles_names as $slug => $name) {
					$wp_user->remove_role( $slug );
				}
				
				$wp_user->add_role( $role );
			}
			
			restore_current_blog();
			unset($roles, $wp_user);
		}
	}
}

function asd_change_user_role_sitewide_hook() {
	asd_change_user_role_sitewide('USERNAME_to_MOD', 'ROL_to_SWITCH_to');
}

add_action('init','asd_change_user_role_sitewide_hook');
and for security sake, comment out the entire block once finished.

Post Reply