Automatically Delete Users After 7 Days In WordPress

[ad_1]

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' );
[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads