Bulk Migrate Users to New Blog on WordPress Multisite

Bulk Migrate Users

Recently I had to move a large number of users from one blog to another on a Multisite install. These users had been mistakenly added to the wrong blog and most of them also had been assigned the wrong role. There were plugin options to do this one by one, but not to bulk migrate users. There were too many users to do it manually.
I needed to get a list of users in the source blog, filter out the users that I didn’t want to modify, move the ones I did, then delete the users that had been moved from the source blog.

Code to Bulk Migrate Users:

$targetblog = 3; // The id of my target blog
 $role = 'agent'; // Custom role
 
 // First I retrieved all of the users in the source blog
 $blogusers = get_users( 'blog_id=1' ); 
 
 // Loop through the Array of WP_User objects.
 foreach ( $blogusers as $user ) {

 // I wanted to only migrate users that weren't already members of the target blog
 // In this case there were only subscribers, agents, and administrators in the database. 
 // Each user had exactly one role. I wanted to move subscribers and agents, 
 // so I used the following check:
 if (! is_user_member_of_blog( $user->ID, $targetblog ) && $user->roles[0] != 'administrator'){
 
 // The following line is only there to give me a bit of a log of events, and to verify that 
 // the correct users were been moved, prior to doing the actual migration operation
 echo '<hr><span>Migrating: ' . $user->ID. ' - ' . esc_html( $user->user_email ) . ' - ' .$user->roles[0] .'</span><br>';
 
 if ( add_user_to_blog( $targetblog, $user->ID, $role ) ) {
 echo 'Added user '.$user->ID.' as '.$role;
 // remove the user from the source blog, and asign their posts to user ID 2
 if ( remove_user_from_blog($user->ID, 1, 2) ) {
 echo 'Removed from source blog';
 } else {
 echo 'Failed to remove user ';
 }
 } else {
 echo 'Failed to add user '.$user->ID.' as '.$role;
 }
 }
 
 }

Some of the important WordPress functions needed to bulk migrate users are:
is_user_member_of_blog
add_user_to_blog
remove_user_from_blog

…among others!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.