comments_number()WP 0.71

Displays the number of comments for a post. Notifications and pings are included in the count. For use within the WordPress Loop.

Use get_comments_number() when you need to get the int itself, not a ready-made message.

1 time — 0.000071 sec (very fast) | 50000 times — 1.61 sec (fast)

No Hooks.

Returns

null. Displays text on the screen.

Usage

<?php comments_number( $zero, $one, $more, $post_id ); ?>
$zero(string)
Text that will be shown if there are no comments.
Default: 'No comments'
$one(string)
Text that will be shown if there is only 1 comment.
Default: '1 comment'
$more(string)
Text that will be shown if there are more than 1 comment.
Default: '% comments'
$post_id(int/WP_Post)
ID or object of the post whose number of comments needs to be retrieved.
Default: 0 (global $post)

Examples

0

#1 Number of post comments

Display the number of article comments and specify what text to display, with a certain number of comments.

Comment count zero – no comments yet; comment count one – one comment; more than one comment (total 42) displays 42 comments.

<p>
This post has <?php comments_number( 'no comments yet', 'one comment', '% comments'); ?>.
</p>
0

#2 link to comments

Let's display a link to comments for each post announcement on the category page, where the anchor of the link will be the number of post comments:

<a href="<?php the_permalink() ?>#comments">
	<?php comments_number( 'no comments', '1 comment', '% comments'); ?>
</a>
0

#3 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>
<?php
printf(
	_nx( 'One Comment', '%1$s Comments', get_comments_number(), 'comments title', 'textdomain' ),
	number_format_i18n( get_comments_number() ) 
);
?>
</h3>
0

#4 Usage of comments_number filter

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;
}

The use of _n() can simplify the above function definition to one line:

return _n( '1 Comment', "{$num} Comments", $num );

Changelog

Since 0.71 Introduced.
Since 5.4.0 The $deprecated parameter was changed to $post.

comments_number() code WP 6.9.1

function comments_number( $zero = false, $one = false, $more = false, $post = 0 ) {
	echo get_comments_number_text( $zero, $one, $more, $post );
}