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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 );
}
Method 2
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 );
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0