Auto Delete Users (auto_delete_users)

You do not need to use raw SQL, WordPress already provides WP_User_Query, and even provides examples of date based queries, for example the official docs say that this will retrieve all users registered within the last 12 hours:

$args = array(
    'date_query' => array( 
        array( 'after' => '12 hours ago', 'inclusive' => true )  
    )
);
$user_query = new WP_User_Query( $args );

Taken from: https://developer.wordpress.org/reference/classes/wp_user_query/#date-parameters

Which suggests this might work:

$args = [
    'date_query' => [
        [
            'before' => '6 months ago',
            'inclusive' => true
        ]
    ]
];
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->get_results() ) ) {
    foreach ( $user_query->get_results() as $user ) {
        echo '<p>delete: ' . $user->display_name . '</p>';
    }
} else {
    echo 'No users found.';
}

If you need to use raw SQL to get something in WordPress and you’re not working with custom tables, then it generally means you’ve done something wrong or aren’t aware of an important core API or parameter.

Other things to note:

  • This won’t scale if your site gets popular as there’s no limit on how many users your query fetches, you should run this more often and in batches
  • unless your host has a system level cron job this won’t happen exactly every 6 months, there’ll be a little variance depending on how busy your site is
  • there may be legal and regulatory obligations that require longer than 6 months, if the goal here is to prevent access after a subscription for example then this isn’t the best way (no upsells to re-subscribe? Or message that the 6 months are up?)

Leave a Comment