I have added this to the users as they log into any of the sites on my multisite.

update_user_meta( $user_id, '_last_login', time() );

Now I want to delete all of the users that have not logged in for the past 6 months. I am looking for the sql version of this as I will then include it into a scheduled task to run once a week to clean the database.

        $time = strtotime('-1 hour');
        $user_query = new WP_User_Query(array('meta_key' => '_last_login', 'meta_value' => $time, 'meta_compare' => '<=', 'fields' => 'ID'));

        if (!function_exists('wpmu_delete_user')) {
            include(ABSPATH . "wp-admin/includes/ms.php");

        if ($user_query->results) {
            foreach ($user_query->results as $old_user) {
  • 1
    This is pretty broad. What have you tried? Why SQL instead of wp_delete_user?
    – s_ha_dum
    Commented Feb 10, 2014 at 17:14
  • I want to screen all the users in the database based on the times they last logged in and delete any users that have not logged in for a set amount of time. I added a sample of what I have done above, but think there is a much more streamlined way to make this happen. Commented Feb 10, 2014 at 18:09
  • I understand what you want, but why SQL? And why not use Core functions? A combination of WP_User_Query and wp_delete_user, plus a wp_cron job should do it.
    – s_ha_dum
    Commented Feb 10, 2014 at 18:11
  • Just saw your edit. What about that doesn't work?
    – s_ha_dum
    Commented Feb 10, 2014 at 18:13
  • It works fine but thought there would be a better way in one sql statement. Such as 'Delete from....where...' Commented Feb 10, 2014 at 18:16

1 Answer 1


If your code works, use it.

It ought to be possible to do this in pure SQL and that might even be more efficient, but don't. Rather, unless you are experiencing identifiable issues using the Core code-- timeouts, for example-- and cannot solve them, don't resort to a pure SQL solution.

The reason is that if the database structure or other Core functionality changes, then code based on the Core functions should (probably) survive. Code based in pure SQL might not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.