delete_user
云策文档标注
概述
delete_user 是一个 WordPress 动作钩子,在用户从站点删除前立即触发。它允许开发者在用户删除前执行自定义操作,如清理插件数据或发送通知。
关键要点
- 触发时机:在用户被删除前立即执行,适用于需要访问用户元数据或字段的场景。
- 参数:包括用户 ID ($id)、重新分配文章和链接的用户 ID ($reassign,默认为 null) 和 WP_User 对象 ($user)。
- 多站点注意事项:在多站点安装中,用户仅从站点移除而非数据库删除;网络站点删除可能不触发此钩子,应使用 wpmu_delete_user。
- 相关钩子:deleted_user 在用户删除后触发,注意区分使用。
代码示例
function my_delete_user( $user_id ) {
global $wpdb;
$user_obj = get_userdata( $user_id );
$email = $user_obj->user_email;
$headers = 'From: ' . get_bloginfo( "name" ) . ' ' . "rn";
wp_mail( $email, 'You are being deleted, brah', 'Your account at ' . get_bloginfo("name") . ' is being deleted right now.', $headers );
}
add_action( 'delete_user', 'my_delete_user' );注意事项
- 确保在需要用户数据时使用 delete_user 钩子,而非 deleted_user。
- 在多站点环境中,检查是否需使用 wpmu_delete_user 替代。
原文内容
Fires immediately before a user is deleted from the site.
Description
Note that on a Multisite installation the user only gets removed from the site and does not get deleted from the database.
Parameters
Source
do_action( 'delete_user', $id, $reassign, $user );
Skip to note 3 content
Steven Lin
Example migrated from Codex:
In this example we send a friendly message to a user before their account is deleted a few milliseconds later.
function my_delete_user( $user_id ) { global $wpdb; $user_obj = get_userdata( $user_id ); $email = $user_obj->user_email; $headers = 'From: ' . get_bloginfo( "name" ) . ' <' . get_bloginfo( "admin_email" ) . '>' . "rn"; wp_mail( $email, 'You are being deleted, brah', 'Your account at ' . get_bloginfo("name") . ' is being deleted right now.', $headers ); } add_action( 'delete_user', 'my_delete_user' );Skip to note 4 content
Yong
Example usage
Send email notification when a user is deleted
add_action( 'delete_user', 'wpdocs_delete_user' ); function wpdocs_delete_user( $user_id ) { $user_data = get_userdata( $user_id ); $headers = 'From: ' . get_bloginfo( 'name' ) . ' ' . "rn"; wp_mail( $user_data->user_email, 'We are deleting your account', 'Your account at ' . get_bloginfo( 'name' ) . ' will be deleted.', $headers ); }