get_comments_number()WP 1.5.0

Retrieves the amount of comments a post has.

1 time — 0.000631 sec (slow) | 50000 times — 1.09 sec (fast)
Hooks from the function

Return

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

Usage

get_comments_number( $post );
$post(int|WP_Post)
Post ID or WP_Post object.
Default: global $post

Examples

1

#1 Create an analog of the function comments_number() using get_comments_number():

$num_comments = get_comments_number(); // return (int)

if ( comments_open() ) {

	if ( $num_comments == 0 ) {
		$comments = __('No Comments');
	}
	elseif ( $num_comments > 1 ) {
		$comments = $num_comments . __(' Comments');
	}
	else {
		$comments = __('1 Comment');
	}

	$write_comments = '<a href="' . get_comments_link() .'">'. $comments.'</a>';
}
else {
	$write_comments = __('Comments are off for this post.');
}
0

#2 Number of comments from the post data

As an alternative to this function, the number of comments of a post can be obtained from the post data in the $post variable: $post->comment_count:

global $post;
echo $post->comment_count; //> 123
0

#3 Get specific post Comments Number:

$post = get_post( 123 );

echo get_comments_number( $post ); //> 54

// or 

echo get_comments_number( 123 ); //> 54

Changelog

Since 1.5.0 Introduced.

get_comments_number() code WP 6.4.3

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