Search

Fetching the Comments Count on Single Post

Listen to this article

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 –

  • Template tagsComments Count

    • comments_popup_link

    • comments_number

  • via get_comments_number function

  • via global variable: $post

    • post->comment_count

  • 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.

[space]

Methods which can be used

The comments_number function will return the number of comments and can be used as follows:

[pre]<?php comments_number(‘zero’, ‘one’, ‘more’); ?>[/pre]

Another way is by using post->comment_count as shown below

[pre]<?php echo ‘comment count is: ‘ . $post->comment_count; ?>[/pre]

[space]

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.

[pre]<?php $commentscount = get_comments_number(); echo $commentscount; ?>[/pre]

You can customize this comment count. For example –

[pre]<?php
$commentscount = get_comments_number();
echo ‘(‘ . $commentscount . ‘)’ . ‘ Comments’;
?>[/pre]

 

This will display the comments as follows –

[pre](0) Comments
(1) Comments
(2) Comments[/pre]

 

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.

Omkar Bhagat

Omkar Bhagat

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads