Wordpress- Delete users between two registration dates programatically

How can we delete user between two registration dates programatically in wordpress?

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function get_users_registered_between_date($start='', $end='' ){
     global $wpdb;
     $prefix =$wpdb->prefix;
     $user_table= $prefix.'users';
      
     if( empty($start) )
          $date = date('Y-m-d');
 
     if ( empty($end) )
          $end = $start;
 
     $start_dt = new DateTime($start. ' 00:00:00');
     $s = $start_dt->format('Y-m-d H:i:s');
 
     $end_dt = new DateTime($end.' 23:59:59');
     $e = $end_dt->format('Y-m-d H:i:s');
    
     $sql = $wpdb->prepare("SELECT ID FROM $user_table WHERE 1=1 AND CAST(user_registered AS DATE) BETWEEN %s AND %s ORDER BY user_login ASC",$s,$e);
     $users = $wpdb->get_results($sql);
 
     return $users;
}
 
 
 
$start_date='2015-02-14'// registration date
$end_date='2015-04-17'// registration date
$users= get_users_registered_between_date($start_date, $end_date ); // users list between date  '2015-02-14' and '2015-04-17'
 
require_once(ABSPATH.'wp-admin/includes/user.php' );
foreach($users as $usr){
    $user_id= $usr->ID;
    $roles= array();
    $user = get_userdata( $user_id );
    $capabilities = $user->{$wpdb->prefix . 'capabilities'};
 
    if ( !isset( $wp_roles ) )
        $wp_roles = new WP_Roles();
 
    foreach ( $wp_roles->role_names as $role => $name ) :
 
        if ( array_key_exists( $role, $capabilities ) )
            $roles[]=$role;
 
    endforeach;
    
    if (!in_array("administrator", $roles)) {
       if(wp_delete_user($user_id)){
        echo 'User deleted'.$user_id;
        echo '<br>';
      }
     
    }
}

No comments:

Post a Comment