Auto delete Wordpress users according to time since registering? Auto delete Wordpress users according to time since registering? wordpress wordpress

Auto delete Wordpress users according to time since registering?


You want to have a look at the user_registered column in the wp_users table. Since you're using WordPress, I'll assume that you're also using MySQL — in which case you can use the DATEDIFF() function in your SQL to work out how many days ago they registered.

The SQL to delete everyone who is 30 days old (or older) is:

DELETE FROM `wp_users` WHERE datediff(now(), `user_registered`) >= 30

You can replace the DELETE FROM with SELECT * FROM in that query to see which users the delete would affect, if you want to preview who will be deleted by the query.

You could set this up as a cronjob using the language of your choice, which might be a PHP script that just runs the SQL above. You could then run that at midnight every day by putting the following into your crontab:

0 0 * * * php ~/delete_expired_users.php

If you're new to cronjobs, then that will simply run the command php ~/delete_expired_users.php every day (that's that the * denotes) at hour 0, minute 0 (ie. midnight). Let me know if you need any more detailed instructions.


Personally, I would recommend using a couple of in-house features of Wordpress that will do a neater job of this for you.

The first is to use wp_delete_user() - this will not only remove the user record, but also wipe any associated user_meta and posts, thus keeping your database nice and clean.

The second recommendation is to use wp_schedule_event() - part of the wp-cron set of functions. This might be preferable if you don't have the flexibility or access to set up a crontab on your current host (note about using this below).

wp_schedule_event(time(), 'daily', 'my_dailyClearOut');function my_clearOldUsers() {    global $wpdb;    $query = $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE datediff(now(), user_registered) > 30");    if ($oldUsers = $wpdb->get_results($query, ARRAY_N)) {        foreach ($oldUsers as $user_id) {            wp_delete_user($user_id[0]);        }    }}add_action('my_dailyClearOut', 'my_clearOldUsers');

This should do the trick for you (this is exactly what I'm using at the moment).

It's worth noting that 'wp-cron' functions are not the same as a standard crontab - they are only fired when a user accesses the site, and thus are nowhere near as precise as a standard cron. However, for this particular functionality, you may find this is fine.

Hat-tip to @Sam for the datediff() function - that's neat!


Be aware that wp_schedule_event() will be fired at every page load, which might compromise your site. Better to check if we already have a scheduled event and only than add it.

if( !wp_next_scheduled( 'my_dailyClearOut' ) ) {  wp_schedule_event( time(), 'daily', 'my_dailyClearOut' );  }