On a basic WordPress 3.1 setup with User Access Manager, is it possible to automatically delete users that are x days old?
I have found no plugins for this feature. How would one go about implementing this? Would I be able to set up a cron job with an sql or php query whereby users that are for example 3 days old are automatically deleted from the database once every day? If so, could someone please explain how?
Any help would be greatly appreciated – thanks in advance.
You want to have a look at the
user_registered
column in thewp_users
table. Since you’re using WordPress, I’ll assume that you’re also using MySQL â in which case you can use theDATEDIFF()
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:
You can replace the
DELETE FROM
withSELECT * 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:
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 hour0
, minute0
(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).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.