函数文档

count_user_posts()

💡 云策文档标注

概述

count_user_posts() 函数用于获取指定用户撰写的文章数量。它支持按文章类型筛选,并可选择是否仅统计公开文章,内部使用缓存机制优化性能。

关键要点

  • 函数参数:$userid(用户ID,必填)、$post_type(文章类型,默认为'post',支持数组)、$public_only(是否仅统计公开文章,默认为false)
  • 返回值:返回用户在该文章类型下的文章数量字符串
  • 内部实现:通过 get_posts_by_author_sql() 构建 SQL 查询,并使用 wp_cache_get_salted() 和 wp_cache_set_salted() 进行缓存处理
  • 过滤器:提供 get_usernumposts 过滤器,允许在返回前修改计数结果
  • 版本变更:4.3.0 版本新增 $public_only 参数和数组形式的 $post_type 支持;4.1.0 版本新增 $post_type 参数

代码示例

// 获取用户ID为5的文章数量
echo count_user_posts(5);

// 获取用户ID为5的'book'文章类型数量
echo count_user_posts(5, 'book');

// 获取用户ID为5的公开文章数量
echo count_user_posts(5, 'post', true);

注意事项

  • $public_only 参数为 false 时,会包含私有文章,但不包括已删除或自定义状态的文章
  • 函数返回的是字符串类型的数字,可直接用于输出
  • 相关函数包括 get_posts_by_author_sql()、wp_cache_get_salted() 等,用于辅助查询和缓存

📄 原文内容

Gets the number of posts a user has written.

Parameters

$useridintrequired
User ID.
$post_typearray|stringoptional
Single post type or array of post types to count the number of posts for. Default 'post'.
$public_onlybooloptional
Whether to only return counts for public posts.

Default:false

Return

string Number of posts the user has written in this post type.

Source

function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
	global $wpdb;

	$post_type = array_unique( (array) $post_type );
	sort( $post_type );

	$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
	$query = "SELECT COUNT(*) FROM $wpdb->posts $where";

	$last_changed = wp_cache_get_last_changed( 'posts' );
	$cache_key    = 'count_user_posts:' . md5( $query );
	$count        = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
	if ( false === $count ) {
		$count = $wpdb->get_var( $query );
		wp_cache_set_salted( $cache_key, $count, 'post-queries', $last_changed );
	}

	/**
	 * Filters the number of posts a user has written.
	 *
	 * @since 2.7.0
	 * @since 4.1.0 Added `$post_type` argument.
	 * @since 4.3.1 Added `$public_only` argument.
	 *
	 * @param string       $count       The user's post count as a numeric string.
	 * @param int          $userid      User ID.
	 * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
	 * @param bool         $public_only Whether to limit counted posts to public posts.
	 */
	return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
}

Hooks

apply_filters( ‘get_usernumposts’, string $count, int $userid, string|array $post_type, bool $public_only )

Filters the number of posts a user has written.

Changelog

Version Description
4.3.0 Added $public_only argument. Added the ability to pass an array of post types to $post_type.
4.1.0 Added $post_type argument.
3.0.0 Introduced.

User Contributed Notes