wordpress

Delete user programmatically in wordpress


In Wordpress, How can I delete a user pro grammatically if I have a user ID?

I am using below code.

$user_id = 4;
$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>';
    }
}

It is not working for me. Please help me where am I wrong?


Solution

  • I have found the solution to resolve my issue.I have just added a line in code. Now updated code as given below.

    require_once(ABSPATH.'wp-admin/includes/user.php' );
    $user_id = 4;
    $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>';
        }
    }
    

    It is now working for me.