我知道如何计算每篇帖子的评论数、用户数和总评论数,但我在获取评论时遇到了问题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;
}
最合适的回答,由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\' );