Purge All WordPress Users of a Particular Role

Bulk Delete WordPress Users

Bulk Delete WordPress Users

I needed to delete all of the subscriber level users on one of my sites recently, and couldn’t find an easy way to do it. My solution? Write some code. It was definitely quicker and easier to run this snippet than to manually delete over 7,700 users from my database. Drop this code into an admin page where you can run it as an administrator, and watch it go to work!

If you need to delete authors, editors, or some other role, simple switch “subscriber” on line 3 to your chosen role. Note: it must be a valid WordPress role registered in your site. This code leaves users with posts in the database. If you would like to remove users that have posts, remove the conditional on line 7 and it’s corresponding closing bracket on line 13. Be sure to modify the wp_delete_user function call on line 8 with it’s second argument – this will keep those user’s posts online and attribute them to whatever user ID you specify in the second argument.

<?php 

$all_users = get_users( array( 'role' => 'subscriber' ) );

foreach( $all_users as $single_user ) {
	$users_posts = get_posts( array( 'author' => $single_user->ID ) );
	if( !$users_posts ) {
		if( wp_delete_user( $single_user->ID ) ) {
			echo 'User ' . $single_user->ID . ' deleted.<br />';
		} else {
			echo 'Delete user ' . $single_user->ID . ' failed!<br />';
		}
	}
}

?>

Disclaimer: This code is fast and aggressive. There is no “undoing” this operation. Use this at your own risk, data is NOT recoverable. Also, don’t believe everything you read online … you cannot perform the same function with raw MySQL without completely hosing your database – so don’t even try unless you REALLY know what you’re doing.

Leave a Reply