Add All Multisite Users to One Sub Site

Say you needed to add all the users in your multisite to a single site on that multisite. You can do that like this. With a bit of tweaking you could also copy all users from one site (or multiple sites) to another or multiple other sites.

Granted, you can also do stuff like this with WP CLI, directly in MySQL, csv user import plugins etc. but never hurts to see another path.

function get_everyone(){
	global $wpdb;

	$all_user_ids = $wpdb->get_col( 'SELECT ID FROM wp_users' );//get all the user ids for the network

	$current_blog_id = get_current_blog_id();// get the site where this plugin/function is active

	$main_user_ids =[];
	
        $args = array(
	   'blog_id'      => $current_blog_id,	
 	); 

	$main_users = get_users( $args ); //get the users of the current blog

	foreach ($main_users as $main_user) {
		
		array_push($main_user_ids, $main_user->ID); //push those site-specific users into an array
	};
	
	$unique = array_diff($all_user_ids, $main_user_ids); //get the users who aren't in the site already
	
       

	foreach ($unique as $key => $the_id) {
	        
		add_user_to_blog($current_blog_id, $the_id, 'contributor'); //add the users to the site where this is active as contributors or change that to set a different role
	}
}

add_shortcode( 'everyone', 'get_everyone' ); //run it via shortcode if you want, I often do this just to var_dump or echo out the values and feel good about seeing the stuff happen

Comments on this post

No comments.

Leave a Reply

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL