comments_number()
云策文档标注
概述
comments_number() 函数用于显示当前文章评论数量的语言字符串,基于评论数量输出自定义文本。它调用 get_comments_number_text() 并直接输出结果。
关键要点
- 函数参数包括 $zero(无评论时文本,默认 false)、$one(一条评论时文本,默认 false)、$more(多条评论时文本,默认 false)和 $post(文章 ID 或 WP_Post 对象,默认全局 $post)。
- 内部实现为 echo get_comments_number_text($zero, $one, $more, $post),简化了输出过程。
- 相关函数 get_comments_number_text() 提供相同功能,位于 wp-includes/comment-template.php。
- 版本变更:5.4.0 中将 $deprecated 参数改为 $post,0.71 版本引入。
代码示例
// 示例1:基本使用,显示评论数量文本
comments_number('No comments', 'One comment', '% comments');
// 示例2:使用 printf 和 _nx 创建可翻译的评论标题
printf( _nx( 'One Comment', '%1$s Comments', get_comments_number(), 'comments title', 'textdomain' ), number_format_i18n( get_comments_number() ) );
// 示例3:使用 comments_number 过滤器自定义输出
add_filter( 'comments_number', 'wporg_com_num', 10, 2 );
function wporg_com_num ( $out, $num ) {
if ( 0 === $num ) {
$out = '0 Comments';
} elseif ( 1 === $num ) {
$out = '1 Comment';
} else {
$out = $num . ' Comments';
}
return $out;
}注意事项
- 参数 $zero、$one、$more 为可选,默认 false 时使用主题或语言包中的默认字符串。
- 使用 comments_number 过滤器可以进一步自定义输出格式,如示例所示。
- 确保在循环内或指定 $post 参数以获取正确文章的评论数。
原文内容
Displays the language string for the number of comments the current post has.
Parameters
Source
function comments_number( $zero = false, $one = false, $more = false, $post = 0 ) {
echo get_comments_number_text( $zero, $one, $more, $post );
}
Skip to note 4 content
Codex
Text Response to Number of Comments
Displays text based upon number of comments: Comment count zero – no responses; comment count one – one response; more than one comment (total 42) displays 42 responses.
<p> This post currently has . </p>Skip to note 5 content
Codex
Title For Comments Section
You might want to have a title above your comments section that includes the number of comments. This example shows how to do that and have all the strings also be translatable.
<h3> printf( _nx( 'One Comment', '%1$s Comments', get_comments_number(), 'comments title', 'textdomain' ), number_format_i18n( get_comments_number() ) ); </h3>Skip to note 6 content
MakeWebBetter
Usage of ‘comments_number’ filter
add_filter( 'comments_number', 'wporg_com_num', 10, 2 ); function wporg_com_num ( $out, $num ) { // Two parameter as in filter described if ( 0 === $num ) { $out = '0 Comments'; // If No comments } elseif ( 1 === $num ) { $out = '1 Comment'; // If 1 comment } else { $out = $num . ' Comments'; // More than 1 comment } return $out; }_n()can simplify the above function definition to one line:return _n( '1 Comment', $num . ' Comments', $num );