get_comments_number()
Gets the number of all comments on a post, including notifications and pings.
Used in the WordPress Loop.
Gets the value of the field $post->comment_count
Unlike comments_number(), this function returns an int, not a string.
1 time — 0.000631 sec (slow) | 50000 times — 1.09 sec (fast)
Hooks from the function
Returns
String|Int
. The number of comments.
Usage
$my_var = get_comments_number( $post_id );
- $post_id(integer/object)
- ID of the post for which we want to get the number of comments.
Default: current post
Examples
#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.'); }
#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
#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() get comments number code WP 6.8.1
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 ); }