wp_update_user_counts()
云策文档标注
概述
wp_update_user_counts() 函数用于更新站点用户总数,支持多站点环境下的网络ID参数,返回更新是否成功。
关键要点
- 函数更新用户总数,基于数据库查询计算用户数量。
- 参数 $network_id 可选,默认为 null,在多站点中指定网络ID,非多站点时传递此参数会触发 _doing_it_wrong() 警告。
- 返回布尔值,表示更新操作是否成功。
- 内部使用 update_network_option() 存储用户计数。
代码示例
function wp_update_user_counts( $network_id = null ) {
global $wpdb;
if ( ! is_multisite() && null !== $network_id ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: $network_id */
__( 'Unable to pass %s if not using multisite.' ),
'$network_id'
),
'6.0.0'
);
}
$query = "SELECT COUNT(ID) as c FROM $wpdb->users";
if ( is_multisite() ) {
$query .= " WHERE spam = '0' AND deleted = '0'";
}
$count = $wpdb->get_var( $query );
return update_network_option( $network_id, 'user_count', $count );
}注意事项
- 在非多站点环境中传递 $network_id 参数会触发错误警告,版本 6.0.0 引入此检查。
- 多站点查询会排除标记为 spam 或 deleted 的用户。
- 函数依赖于 update_network_option() 来保存用户计数。
原文内容
Updates the total count of users on the site.
Parameters
$network_idint|nulloptional-
ID of the network. Defaults to the current network.
Default:
null
Source
function wp_update_user_counts( $network_id = null ) {
global $wpdb;
if ( ! is_multisite() && null !== $network_id ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: $network_id */
__( 'Unable to pass %s if not using multisite.' ),
'<code>$network_id</code>'
),
'6.0.0'
);
}
$query = "SELECT COUNT(ID) as c FROM $wpdb->users";
if ( is_multisite() ) {
$query .= " WHERE spam = '0' AND deleted = '0'";
}
$count = $wpdb->get_var( $query );
return update_network_option( $network_id, 'user_count', $count );
}
Changelog
| Version | Description |
|---|---|
| 6.0.0 | Introduced. |