Using WordPress ‘delete_user’ PHP action

The delete_user WordPress PHP action fires immediately before a user is deleted from the database.

Usage

add_action('delete_user', 'your_function_name', 10, 3);

function your_function_name($id, $reassign, $user) {
    // your custom code here
}

Parameters

  • $id (int) – ID of the user to delete.
  • $reassign (int|null) – ID of the user to reassign posts and links to. Default null, for no reassignment.
  • $user (WP_User) – WP_User object of the user to delete.

More information

See WordPress Developer Resources: delete_user

Examples

Send an email when a user is deleted

Sends an email to the site administrator when a user is deleted.

add_action('delete_user', 'notify_admin_user_deleted', 10, 3);

function notify_admin_user_deleted($id, $reassign, $user) {
    $admin_email = get_option('admin_email');
    $message = "User {$user->display_name} ({$user->user_email}) has been deleted.";
    wp_mail($admin_email, 'User Deleted', $message);
}

Log user deletion

Logs user deletion to a custom log file.

add_action('delete_user', 'log_user_deletion', 10, 3);

function log_user_deletion($id, $reassign, $user) {
    $log_message = "User {$user->display_name} (ID: {$id}) deleted at " . current_time('mysql') . PHP_EOL;
    error_log($log_message, 3, '/path/to/your/user_deletion.log');
}

Reassign posts to a specific user

Reassigns the deleted user’s posts to a specific user (e.g., user with ID 2).

add_action('delete_user', 'reassign_posts_to_user', 10, 3);

function reassign_posts_to_user($id, $reassign, $user) {
    $reassign = 2;
    return $reassign;
}

Remove user meta data

Removes all user meta data associated with the deleted user.

add_action('delete_user', 'remove_user_meta_data', 10, 3);

function remove_user_meta_data($id, $reassign, $user) {
    delete_metadata('user', $id, '', '', true);
}

Delete user’s comments

Deletes all comments made by the deleted user.

add_action('delete_user', 'delete_users_comments', 10, 3);

function delete_users_comments($id, $reassign, $user) {
    $comments = get_comments(array('user_id' => $id));
    foreach ($comments as $comment) {
        wp_delete_comment($comment->comment_ID, true);
    }
}