update_user_status()
云策文档标注
概述
update_user_status() 是一个 WordPress 函数,用于更新用户在数据库中的状态,如标记为垃圾(spam)或非垃圾(ham)。该函数自 WordPress 5.3.0 起已弃用,建议使用 wp_update_user() 替代。
关键要点
- 函数已弃用:自 WordPress 5.3.0 起,update_user_status() 被标记为弃用,推荐使用 wp_update_user() 进行用户状态更新。
- 核心用途:主要用于多站点(Multisite)环境中更新用户状态,如设置 spam、ham 或 deleted 状态。
- 参数说明:接受用户 ID、状态列名(如 'user_status'、'spam'、'deleted')、新状态值和一个已弃用的可选参数。
- 返回值:返回传入的新状态值。
- 相关钩子:触发 make_spam_user 和 make_ham_user 动作钩子,用于在用户状态变更后执行自定义操作。
- 注意事项:仅适用于多站点安装,单站点安装中可能无法正常工作。
代码示例
// 标记用户为垃圾
$user_id = 394;
update_user_status( $user_id, 'spam', 1 );
// 标记用户为非垃圾
$user_id = 394;
update_user_status( $user_id, 'spam', 0 );注意事项
- 弃用警告:使用此函数会触发 _deprecated_function() 警告,建议迁移到 wp_update_user()。
- 多站点限制:函数功能依赖于多站点环境,单站点安装中可能无效。
- 参数处理:状态列名通过 sanitize_key() 进行清理,确保数据库操作安全。
原文内容
Update the status of a user in the database.
Description
Previously used in core to mark a user as spam or “ham” (not spam) in Multisite.
See also
Parameters
$idintrequired-
The user ID.
$prefstringrequired-
The column in the wp_users table to update the user’s status in (presumably user_status, spam, or deleted).
$valueintrequired-
The new status for the user.
$deprecatednulloptional-
Deprecated as of 3.0.2 and should not be used.
Default:
null
Source
function update_user_status( $id, $pref, $value, $deprecated = null ) {
global $wpdb;
_deprecated_function( __FUNCTION__, '5.3.0', 'wp_update_user()' );
if ( null !== $deprecated ) {
_deprecated_argument( __FUNCTION__, '3.0.2' );
}
$wpdb->update( $wpdb->users, array( sanitize_key( $pref ) => $value ), array( 'ID' => $id ) );
$user = new WP_User( $id );
clean_user_cache( $user );
if ( 'spam' === $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/user.php */
do_action( 'make_spam_user', $id );
} else {
/** This filter is documented in wp-includes/user.php */
do_action( 'make_ham_user', $id );
}
}
return $value;
}
Hooks
- do_action( ‘make_ham_user’, int $user_id )
-
Fires after the user is marked as a HAM user. Opposite of SPAM.
- do_action( ‘make_spam_user’, int $user_id )
-
Fires after the user is marked as a SPAM user.
Changelog
| Version | Description |
|---|---|
| 5.3.0 | Deprecated. Use wp_update_user() |
| 3.0.0 | Introduced. |
Skip to note 2 content
Codex
Basic Example
Mark a User as Spam
Note: You can only do this on multisite installs!
$user_id = 394; update_user_status( $user_id, 'spam', 1 );Mark a User as Ham
$user_id = 394; update_user_status( $user_id, 'spam', 0 );Again, this will not work on single site installs.