User deletion hooks
August 8, 2025 Β· AI Conversations
—
### β Recommended Hook: `delete_user`
add_action('delete_user', 'your_custom_user_delete_handler');
function your_custom_user_delete_handler($user_id) {
// Perform any cleanup tasks
error_log("User with ID $user_id is about to be deleted.");
// Example: delete custom data
// delete_user_meta($user_id, 'your_custom_meta_key');
}
—
### π Difference between `delete_user` and `deleted_user`
| Hook | Timing |
|—————-|———————————-|
| `delete_user` | Fires **before** user is deleted |
| `deleted_user` | Fires **after** user is deleted |
You can use either depending on your need. For example:
add_action('deleted_user', 'after_user_deleted_cleanup');
function after_user_deleted_cleanup($user_id) {
// Cleanup actions after user has been deleted
error_log("User with ID $user_id has been deleted.");
}
—
### π Only in Admin Panel?
These hooks are triggered **regardless of where** the user is deleted from (admin panel or programmatically). If you want to ensure the action happens **only from the admin panel**, you can check:
if (is_admin()) {
add_action('delete_user', 'admin_only_user_delete');
}
function admin_only_user_delete($user_id) {
// Logic only for admin-triggered deletions
}
—
Let me know if you want to log deleted WooCommerce user data, order association, or anything else during this process.
Hereβs the full code:
add_action('delete_user', 'unassign_customer_from_orders');
function unassign_customer_from_orders($user_id) {
// Get all order IDs assigned to this user
$orders = get_posts([
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array_keys(wc_get_order_statuses()),
'meta_query' => [
[
'key' => '_customer_user',
'value' => $user_id,
'compare' => '='
]
],
'fields' => 'ids'
]);
if (!empty($orders)) {
foreach ($orders as $order_id) {
update_post_meta($order_id, '_customer_user', 0);
}
}
}
—
### β What This Does:
– When a user is deleted from the WordPress admin…
– It finds all orders where `_customer_user` matches that user's ID.
– It sets `_customer_user` to `0`, marking them as a "guest" order.
—
Let me know if you want to:
– Also **add a note** to the order (e.g., "User deleted").
– Or **reassign** those orders to another admin/user instead of setting to 0.
UPDATE wp_postmeta
SET meta_value = '0'
WHERE meta_key = '_customer_user';
—
### β οΈ Important Notes:
– Replace `wp_` with your actual database table prefix if it's different.
– This will affect **every order**, not just deleted users.
– Make a **full database backup** before running this in production.
—
### π Optional PHP Version (Direct DB Query):
If you want to run this inside a WordPress plugin or function using `$wpdb`:
global $wpdb;
$wpdb->query("
UPDATE {$wpdb->postmeta}
SET meta_value = '0'
WHERE meta_key = '_customer_user'
");
Let me know if you want to:
– Restrict this only to specific users or date ranges.
– Log which orders were affected.
– Automatically trigger this after user deletion.