统计自定义帖子类型的所有评论

时间:2014-02-12 作者:Sagive

我知道如何计算每篇帖子的评论数、用户数和总评论数,但我在获取评论时遇到了问题the total amount of comments post in a specific post type.

我想我可以循环浏览所有帖子并统计每个帖子的评论,但我正在寻找速度更快、资源成本更低的帖子

感谢您的帮助

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 个回复
最合适的回答,由SO网友:Bainternet 整理而成

直接sql和一个简单的子查询如何,首先获取自定义帖子类型的所有帖子ID,例如:

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\');

SO网友:kaiser

只需执行一个简单的MySQL查询sum是的comment_count 一行以下插件为例:

<?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
    ) );
}
然后,您可以调用它来显示此帖子类型的总金额。

echo \\WSPE\\commentCountTotal( \'your-post-type\' );

结束

相关推荐

COMMENTS_POPUP_LINK()-如何根据不同的评论条件加载不同的类/图片?

作为Codex 表示语法:<?php comments_popup_link( $zero, $one, $more, $css_class, $none ); ?> 很明显,我们可以根据不同的注释条件加载不同的文本,如“注释打开”、“1注释”、“2+注释”和“注释关闭”,此外,我们还可以将CSS类加载到该部分。我想从具有不同注释条件的图像精灵加载不同的图像:评论打开但未发布时-发布评论时加载一条-关闭评论时加载一条-加载一条What I thought。。。就是加载不同的类,这样我