Using WordPress PHP code, how to bulk delete only 100 subscribers at a time from thousands of users?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/385266

  •  19-05-2021
  •  | 
  •  

Question

Using WordPress PHP code, how to bulk delete ONLY 100 subscribers at a time from thousands of users?

(The following code tries to delete all 50k users at once and my server hangs. If I can delete only 100 users at a time then I can use a Cron job every 5 minutes.)

<?php
$blogusers = get_users( ‘role=subscriber’ );
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
$user_id = $user->ID;
wp_delete_user( $user_id );
}

Thanks.

Was it helpful?

Solution

Here you will find all parameters supported by get_users().

$blogusers = get_users( [
   'role'   => 'subscriber',
   // limit the number of rows returned
   'number' => 100,
] );

foreach ( $blogusers as $user ) {
   wp_delete_user( $user->ID );
}

Or return only ID:

//  $blogusers is array of IDs
$blogusers = get_users( [
   'role'   => 'subscriber',
   // return only user ID
   'fields' => 'ID',
   // limit the number of rows returned
   'number' => 100,
] );

foreach ( $blogusers as $user_id ) {
   wp_delete_user( $user_id );
}

OTHER TIPS

You can use break statement

<?php
$blogusers = get_users( ‘role=subscriber’ );
$i = 0;
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
if(++$i > 100) break;
$user_id = $user->ID;
wp_delete_user( $user_id );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top