This is not the type of function you would require to use very often because it offers very specific feature to
automatically delete users after predefined time. I was looking to implement this feature in a past project where my client was offering temporary access to a section on his website to many users, but he also wanted to revoke their access after a week. Deleting users manually from database worked for a while but later he
often forgot to delete uses from database on timely basis which caused him lot of trouble and that’s when he asked to find a better solution to
automatically delete users after 7 days.
To do this I had to run a SQL query in WordPress to periodically check if there are users older than 7 days in WordPress users database table, and if there are, then delete those users at once. So I created this following function to delete used after 7 days of time.
Simply paste this WordPress snippet in your theme’s functions.php file to automatically delete users after 7 days of time. Of course you can change this time limit and make it as small as 1 day or whatever time limit you prefer.
// automatically delete users after 7 days in wordpress
function wcs_auto_delete_users() {
global $wpdb;
$query = $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE datediff( now(), user_registered ) > 7" );
if ( $oldUsers = $wpdb->get_results( $query, ARRAY_N ) ) {
foreach ( $oldUsers as $user_id ) {
wp_delete_user( $user_id[0] );
}
}
}
add_action( 'wcs_daily_clean_database', 'wcs_auto_delete_users' );
wp_schedule_event( time(), 'daily', 'wcs_daily_clean_database' );
Hi, I like a lot this blog, I have a question about this sistem, would be possible to delete users by role instead dete them by days?
thank you, you do very nice job on this site. =)
Take a look:
Best Regards
Patrick
There is a little mistake in my script.
replace
wp_delete_user([0]);
withwp_delete_user($user_id[0]);
Thanks admins for editing!
Thanks Patrick for this handy WordPress snippet.
I have edited and corrected your snippet for changes you mentioned. Although I have not tested it personally but I am sure it must be working.
But please people who use this, keep a backup of your database before trying. In case you want to revert back the changes. :)
Thanks Patrick again. You are awesome.
Hello thanks for this tutorial. Is possibile to customize the code to change the user role for a specifi user?
Also is possibile send email to use to comunicate change user?
Thanks
Hi,
Have possible to delete users by role wise ? Subscribers = 30 Days, Editors = 40 Days, Authors = 60 days.
Regards
Uncaught Error: Call to undefined function wp_delete_user()