WordPress 已经提供文章、评论和用户计数函数,不需要手写 SQL。
$post_counts = wp_count_posts( 'post' );
$comment_counts = wp_count_comments();
$user_counts = count_users();
$published_posts = (int) $post_counts->publish;
$approved_comments = (int) $comment_counts->approved;
$total_users = (int) $user_counts['total_users'];
wp_count_posts() 返回不同状态的文章数,因此公开页面通常读取 publish,不要把草稿或回收站算进去。wp_count_comments() 返回 approved、moderated、spam、trash 等字段。count_users() 返回总用户数和各角色数量。
printf(
esc_html__( '共 %1$d 篇文章、%2$d 条评论、%3$d 位用户', 'weixing' ),
$published_posts,
$approved_comments,
$total_users
);
大站点不应在每个前台请求中重复计算用户角色分布;可用 transient 或对象缓存保存结果,并在相关内容发生变化后清理。公开用户总数前也应确认这符合站点的隐私设计。
