Friday, June 10, 2016

Wordpress- Delete user programatically

global $wpdb;
$curr_date= date('Ymd');

require_once(ABSPATH.'wp-admin/includes/user.php' );
$users = get_users(array(
    'meta_key'     => 'user_delete_date',
    'meta_value'  => "$curr_date",
));

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>';
      }
   
    }
}

4 comments :

  1. If I want to delete users between a date range, how can I achive the same.

    ReplyDelete
    Replies
    1. Hi @napster,

      I think you want delete users between tow registration dates.
      If ok, hope below post will help you.

      http://developeraftab.blogspot.in/2016/06/wordpress-delete-users-between-tow.html

      Thanks,
      Aftab

      Delete
  2. Hi, I want to delete user and wants to maintain history of users. How can I do that in WP.

    ReplyDelete
    Replies
    1. Hi pr k,

      To maintain history of deleted users , you will have to do custom coding. For this you can use custom table and user info will be inserted in table as soon as the user going to delete by script.

      Hope this will help.

      Thanks,
      Aftab

      Delete