Removing orphan users in WordPress Multisite

You’ll need to select all available users (see $users below) to loop through each one and decide if it’s a demouser; to delete all users with no associated site (see empty($user_blogs) below) you can call wpmu_delete_user() (this will require to load ms.php, if you’re loading it within a theme or plugin).

Just add the following snippet right after the part in your code where you’re deleting the blogs:

global $wpdb;
$users = $wpdb->get_results("SELECT ID, user_login FROM $wpdb->users");

foreach ( $users as $user ) :

    $user_login = $user->user_login; // get login
    $user_id = $user->ID; // get ID

    // check for name
    if ( $user_login == 'demouser' ) :

        $user_blogs = get_blogs_of_user( $user_id ); // get related sites

        // check if empty
        if ( empty($user_blogs) ) :
            require_once ABSPATH . 'wp-admin/includes/ms.php';
            wpmu_delete_user( $user_id ); // delete user
        endif;

    endif;

endforeach;

Please take care of this as it will delete the unassigned users and you’ll not be able to restore deleted users!

Leave a Comment