Using WordPress ‘get_comments_number()’ PHP function

The get_comments_number() WordPress PHP function retrieves the number of comments a post has.

Usage

get_comments_number( $post )

Example:

Input:

get_comments_number( $post->ID );

Output:

5

Parameters

  • $post (int|WP_Post) (Optional) – Post ID or WP_Post object. Default is the global $post.

More information

See WordPress Developer Resources: get_comments_number()

Examples

Display the number of comments for the current post

This example will display the number of comments for the current post.

// Inside the loop
echo 'This post has ' . get_comments_number() . ' comments.';

Display the number of comments for a specific post

This example will display the number of comments for a specific post with a given ID.

$post_id = 42; // Set the desired post ID
echo 'Post ' . $post_id . ' has ' . get_comments_number( $post_id ) . ' comments.';

Customize the comment text based on the number of comments

This example customizes the displayed text based on the number of comments a post has.

$comments_number = get_comments_number();

if ( $comments_number == 0 ) {
    echo 'No comments yet';
} elseif ( $comments_number == 1 ) {
    echo '1 comment';
} else {
    echo $comments_number . ' comments';
}

This example displays the number of comments with a link to the comments section in the post.

echo '<a href="' . get_comments_link() . '">' . get_comments_number() . ' comments</a>';

Use get_comments_number() with get_the_title()

This example displays the post title and the number of comments.

// Inside the loop
echo 'The post "' . get_the_title() . '" has ' . get_comments_number() . ' comments.';