Count all comments of a custom post type

I know how to count comment per post, user and in total but i am
having problems getting the total amount of comments post in a specific post type.

I guess i can loop trough all the posts and count each one
comments but i am looking for something faster and less
resource expensive

Read More

Appreciate your help

I got this so far (i think this is a bad way but i might be wrong):

/*** ALL COMMENTS COUNT BY POST TYPE ***/
function countCptCommentsTotal() {

    // FAQ ARGS
    $faqStatsArgs = array(
        'post_type'         =>  'some_post_type',
        'post_status'       =>  'publish',
        'posts_per_page'    =>  -1
    );
    $faqstats_query = new WP_Query($faqStatsArgs);

    // THE LOOP
    $allAnswers = 0;
    while ($faqstats_query->have_posts()) {
        $faqstats_query->the_post();

        $curfaqid       =   get_the_ID();
        $allAnswers =   $allAnswers + countPostComments($curfaqid);

    }

    wp_reset_query();
    return $allAnswers;
}

Related posts

2 comments

  1. How about direct sql with a simple subquery to first get all the post ids of your custom post type ex:

    function get_all_comments_of_post_type($post_type){
      global $wpdb;
      $cc = $wpdb->get_var("SELECT COUNT(comment_ID)
        FROM $wpdb->comments
        WHERE comment_post_ID in (
          SELECT ID 
          FROM $wpdb->posts 
          WHERE post_type = '$post_type' 
          AND post_status = 'publish')
        AND comment_approved = '1'
      ");
      return $cc;
    }
    

    Usage:

    $total_comments =  get_all_comments_of_post_type('some_post_type');
    
  2. Simply do a plain MySQL Query that sums the comment_count row. The following plugin as an example:

    <?php
    namespace WPSE;
    
    /**
     * Plugin Name: (#134338) Get total Comment Count
     * Plugin URl:  http://wordpress.stackexchange.com/q/134338
     */
    
    defined( 'ABSPATH' ) or exit;
    
    function commentCountTotal( $postType = 'post' )
    {
        global $wpdb;
        return $wpdb->query( $wpdb->prepare(
            "SELECT sum( comment_count )
            FROM (
                SELECT comment_count
                FROM {$wpdb->posts}
                WHERE post_type = '%s'
                AND post_status = 'publish'
                AND comment_count > 0
                LIMIT 0 , 999
            ) as count",
            $postType
        ) );
    }
    

    You can then just call it to display the total amount of this post type.

    echo WSPEcommentCountTotal( 'your-post-type' );
    

Comments are closed.