Last active
October 14, 2021 14:09
-
-
Save adczk/6de168eab24ebfbae49f834b571c26c3 to your computer and use it in GitHub Desktop.
WP Multisite: Remove user from all blogs and delete account if removed from one blog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
######################################## | |
# | |
# Sitewide user removal if removed from one blog on WP Multisite | |
# | |
# use as MU plugin | |
# | |
# Note: this is basic code with no additional security checks | |
# and error prevention | |
# and it doesn't reassign user content (it's left "free floating") | |
# | |
# USE AT YOUR OWN RISK!!! | |
# | |
# UPDATE: Nov 14th 2021 | |
# * fixed: new accounts couldn't be added to blogs | |
# | |
######################################## | |
function sitewide_remove_user_do_delete_site( $user_id, $blog_id ) { | |
switch_to_blog( $blog_id ); | |
$user = get_userdata( $user_id ); | |
if ( ! $user ) { | |
restore_current_blog(); | |
return new WP_Error( 'user_does_not_exist', __( 'That user does not exist.' ) ); | |
} | |
$user->remove_all_caps(); | |
restore_current_blog(); | |
return true; | |
} | |
function sitewide_remove_user( $user_id , $blog_id, $reassign ) { | |
global $wpdb; | |
// bail if it's not user list screen (to avoid execution when adding new user) | |
if ( ( ! function_exists( 'get_current_screen' ) ) || ( 'users' !== get_current_screen()->base ) ){ | |
return false; | |
} | |
$user_id = (int) $user_id; | |
$user = new WP_User( $user_id ); | |
// bail if user doesn't exist | |
if ( ! $user->exists() ) { | |
return false; | |
} | |
// execute only if not super-admin account | |
if (! is_super_admin( $user_id ) ) { | |
// get all sites of user | |
$sites = get_blogs_of_user( $user_id ); | |
foreach ( $sites as $key=>$value) { | |
// and delete from network skipping current blog | |
// as this one is handled by WP core anyway | |
if ( $blog_id <> $key ) { | |
if ( sitewide_remove_user_do_delete_site( $user_id, $key ) ) { | |
error_log( 'User '. $user_id . ' removed from blog ' . $blog_id ); | |
} | |
else { | |
error_log( 'ERROR: User '. $user_id . ' removed from blog ' . $blog_id ); | |
} | |
} | |
} | |
// delete user account from network | |
$meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $user_id ) ); | |
foreach ( $meta as $mid ) { | |
delete_metadata_by_mid( 'user', $mid ); | |
} | |
$wpdb->delete( $wpdb->users, array( 'ID' => $user_id ) ); | |
clean_user_cache( $user ); | |
} | |
} | |
add_action( 'remove_user_from_blog', 'sitewide_remove_user', 10,32 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment