函数文档

get_comments_number()

💡 云策文档标注

概述

get_comments_number() 函数用于检索文章的评论数量,支持指定文章 ID 或 WP_Post 对象,并可通过过滤器进行自定义。

关键要点

  • 参数 $post 可选,默认为全局 $post,可接受文章 ID 或 WP_Post 对象
  • 返回值:文章存在时返回评论数量的数字字符串,否则返回 0
  • 提供 get_comments_number 过滤器,允许开发者修改返回的评论计数
  • 函数内部调用 get_post() 获取文章数据,并基于 comment_count 属性计算

代码示例

// 获取当前文章的评论数量
echo get_comments_number();

// 获取指定文章的评论数量
echo get_comments_number($post->ID);

📄 原文内容

Retrieves the amount of comments a post has.

Parameters

$postint|WP_Postoptional
Post ID or WP_Post object. Default is the global $post.

Return

string|int If the post exists, a numeric string representing the number of comments the post has, otherwise 0.

Source

function get_comments_number( $post = 0 ) {
	$post = get_post( $post );

	$comments_number = $post ? $post->comment_count : 0;
	$post_id         = $post ? $post->ID : 0;

	/**
	 * Filters the returned comment count for a post.
	 *
	 * @since 1.5.0
	 *
	 * @param string|int $comments_number A string representing the number of comments a post has, otherwise 0.
	 * @param int        $post_id Post ID.
	 */
	return apply_filters( 'get_comments_number', $comments_number, $post_id );
}

Hooks

apply_filters( ‘get_comments_number’, string|int $comments_number, int $post_id )

Filters the returned comment count for a post.

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes