Using WordPress ‘comments_number()’ PHP function

The comments_number() WordPress PHP function displays the language string for the number of comments a current post has.

Usage

Let’s say you want to display the number of comments on a blog post. You can use the comments_number() function like this:

comments_number('No comments yet', 'One comment', '% comments');

In this case, if there are no comments, the text “No comments yet” will be displayed. If there is one comment, it will show “One comment”. If there are multiple comments, it will display the number of comments, like “5 comments”.

Parameters

  • $zero (string|false) Optional: Text for no comments. Default: false
  • $one (string|false) Optional: Text for one comment. Default: false
  • $more (string|false) Optional: Text for more than one comment. Default: false
  • $post (int|WP_Post) Optional: Post ID or WP_Post object. Default is the global $post.

More information

See WordPress Developer Resources: comments_number()

Examples

Displaying Comment Count Text

This code snippet will show a different message depending on the number of comments on a post.

comments_number('No responses yet', 'One response', '% responses');

Title for Comments Section

You can use comments_number() function to display a title above your comments section that includes the number of comments.

printf( _nx( 'One Comment', '%1$s Comments', get_comments_number(), 'comments title', 'textdomain' ), number_format_i18n( get_comments_number() ) );

Using comments_number Filter

The comments_number() function can also be used with filters. In the example below, a filter is used to modify the output of the comments_number() function.

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

Simplified Use with _n()

The _n() function can simplify the comments_number() function to a single line.

return _n( '1 Comment', $num . ' Comments', $num );