Count the number of approved comments for a post

 * Gets comment count of post.
 * example: [comment_count post="5"]
 * @param   $atts[]                 post            the post id
 * @return  html
function wpsnippit_post_comment_count($atts, $content = 'null'){
    extract( shortcode_atts(  array(
            'post' => '',
       ), $atts ) 
    if($post != ''){
        //setup variables
        $commentCount = wp_count_comments($post); //does it hurt?
        return '<br><span class="answered-text"><span class="number">' 
                          . $commentCount->approved . 
               '</span> comments</span>';
add_shortcode( 'comment_count', 'wpsnippit_post_comment_count' );

Recently I came across an issue where I needed to come up with an easy way to display the number of approved comments associated with a specific post in a specific category. What made the task even harder was that the client used a page builder plugin to create the page I was working on, so I couldn’t just copy a template file into my child theme and make changes there. It meant that I had to write a custom function around shortcode.

The concept is easy enough. Place this in your child theme’s functions.php file. The function returns some HTML and a count of approved comments for the post we asked for. To use, simply add the shortcode [comment_count post=”post_id”] where post_id is the ID number of your category.

Find the category ID for the comments shortcode
You can easily find the category ID by navigating to Posts > Categories and clicking the category name you want the ID for. Once there, look in the address bar for the number after category&tag_ID=. That will be the category ID. Copy and paste the category ID in the shortcode.

Results of approved comments shortcode
The results look something like this.