John Doey
John Doey

Reputation: 1

Automatically delete user based on custom field entry on WordPress

I already have a code snippet to auto-delete users based on registration, but I'm currently using a csv user importer plugin, with custom field support e.g. age, address and organization. I want something like for example, if user matches the custom field entry, Google - then delete after 3 years, if user matches Microsoft, delete after 5 years.

This is the code snippet for just auto-delete user, I don't know how to modify it any further please help.

    global $wpdb;
    $userlevel = 0; //0 = subscriber
    $deleteafter = 1095; //deleter User after 1095 days

    $query = $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users LEFT JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE $wpdb->usermeta.meta_key = %s AND $wpdb->usermeta.meta_value = %d AND DATEDIFF(CURDATE(), $wpdb->users.user_registered) > %d", $wpdb->prefix.'user_level',$userlevel,$deleteafter);


    if($oldUsers = $wpdb->get_results($query, ARRAY_N)){
        foreach ($oldUsers as $user_id) {
            wp_delete_user($user_id[0]);
        }
    }
}

add_action('daily_clean_database', 'auto_delete_users');

wp_schedule_event(time(), 'daily', 'daily_clean_database');```

Upvotes: 0

Views: 224

Answers (1)

Gene Sescon
Gene Sescon

Reputation: 300

You can check the user meta field since you already got the user_id.

$custom_field_entry = get_user_meta($user_id[0], 'custom_field_entry', true);

if($custom_field_entry == 'Google') {
   // Your Delete Function
} else if($custom_field_entry == 'Microsoft') {
    // Your Delete Function
}

Put this snippet inside your foreach.

Check this one out. https://developer.wordpress.org/reference/functions/get_user_meta/

Upvotes: 1

Related Questions