Many a times we need to fetch the total number of comments on a single post or display that number on the excerpt. It seems pretty easy but actually there are many ways to fetch the number of comments in WordPress. For instance –
via get_comments_number function
via global variable: $post
other custom ways
Now the comments_popup_link works only inside the loop and doesn’t really work on is_single() or is_page(). In simple terms, it works only on homepage or archive pages. So let’s not talk about this function.
Methods which can be used
The comments_number function will return the number of comments and can be used as follows:
<?php comments_number(‘zero’, ‘one’, ‘more’); ?>
Another way is by using post->comment_count as shown below
<?php echo ‘comment count is: ‘ . $post->comment_count; ?>
Preferred Method To Add Comments Number
But these are all somewhat complex and relatively difficult to customize or implement. The most easiest way is to use get_comments_number function.
<?php $commentscount = get_comments_number(); echo $commentscount; ?>
You can customize this comment count. For example –
<?php $commentscount = get_comments_number(); echo ‘(‘ . $commentscount . ‘)’ . ‘ Comments’; ?>
This will display the comments as follows –
(0) Comments (1) Comments (2) Comments
You can see, how easy it is to implement get_comments_number() function. Also it’s very simple to customize it with a bit of PHP code.
And hey, I’m sure some of you are wondering about the 1 Comment’S’ part. Well we can of course change that 1 ‘commentS’ to 1 comment using an If Else code.