Removing orphan users in WordPress Multisite

I’ve set up WP Multisite and wrote a function to daily delete all the blogs apart from one. Now when you use the wpmu_delete_blog() function the blogs are removed however their users remain, and are not associated to any site. I want to get all those users and remove them straight after deleting the blogs. All the users I create are given the role ‘demouser’. How can I do this?

1 Answer
1

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