1

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

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;
}
2
  • Then please show us what you got.
    – kaiser
    Feb 12 '14 at 13:23
  • hey @kaiser - added the method i mentioned in my question.
    – Sagive
    Feb 12 '14 at 13:28
2

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
  • This looks gr8 @bainternet ;) - testing...
    – Sagive
    Feb 12 '14 at 13:36
  • 1
    i must polish my sql query abilities - could have saved some time. as always - thanks for your help ;)
    – Sagive
    Feb 12 '14 at 13:45
1

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 \WSPE\commentCountTotal( 'your-post-type' );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.