Tips and Tricks

WordPress: Get Count For Approved Comments Outside The Loop

If you are a Web Developer and you work with WordPress, then there may have been a situation where you needed to get the count for  comments that were only in “Approved” state for a specific post. Note that this is different from the total comments count. So do you know how to get the comments count for Approved comments in WordPress? If not, then this article is for you. In this article, I am going to share a very easy way to get the count for all comments that are either Approved, Moderated, or in Spam and in Trash.

How to get comments count in WordPress for different comment states (Approved, Moderated, Spam, Trash ) outside WordPress loop

In order to get the comments count outside of the loop, we use the following function:

<?php wp_count_comments( $post_id ); ?>

post_id (optional) - The ID of the post for which you want to get the comments count and it is optional inside the loop

In the above function, note that when you use it, you won’t directly get the comment count directly as wp_count_comments returns us an object. So rather you would have to point to the properties inside of the object to get it’s corresponding value. So let’s say we want to get the comments count for post with ID 10. I am going to list all possibilities below:

<?php //10 is the post ID. Mention it explicitly outside the loop. Inside the loop, you would want to use get_the_ID()

$comments_count = wp_count_comments( 10 );

?>

 Get Approved Comments count:

<?php echo "Comments approved: " . $comments_count->approved ; ?>

 Get Count of Comments that are in Moderation:

<?php echo "Comments in moderation: " . $comments_count->moderated ; ?>

 Get Count of Comments that are in Spam:

<?php echo "Comments in Spam: " . $comments_count->spam ; ?>

 Get Count of Comments that are in Trash:

<?php echo "Comments in Trash: " . $comments_count->trash ; ?>

 Get the total count of comments, regardless of their state:

<?php echo "Total Comments: " . $comments_count->total_comments ; ?>
That’s it!

Do you know of any other ways to get comments count in WordPress? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*