php - WooCommerce 统计给定产品类别的评论

标签 php wordpress woocommerce review taxonomy-terms

我需要显示特定类别中所有产品的评论计数。以下代码用于计算所有产品的所有评论(作为评论),但是 get_comments() 似乎未设置为允许分类查询...

function rnr_colors_review_count() {
    $args = array(
        'post_type' => 'product', //Post type 
        'status' => 'approve',  
        'count' => 'true'
         //I would like to insert a taxonomy arg here, but may need another solution.

    );
    $comments_count = get_comments($args);
 
    echo 'Total Comments= ' . $comments_count;
}

最佳答案

您需要使用自定义的轻量级 SQL 查询。我已将该 Sql 查询嵌入到下面的函数中,并带有一个参数:产品类别术语 slug

功能:

function get_products_reviews_count_from_category( $term_slug ){
    global $wpdb;

    return  $wpdb->get_var( $wpdb->prepare( "
        SELECT COUNT(c.comment_post_ID)
        FROM {$wpdb->prefix}comments as c
        LEFT JOIN {$wpdb->prefix}posts as p ON c.comment_post_ID = p.ID
        LEFT JOIN {$wpdb->prefix}term_relationships as tr ON p.ID = tr.object_id
        LEFT JOIN {$wpdb->prefix}term_taxonomy as tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
        JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id
        WHERE c.comment_type = 'review' AND c.comment_approved = '1'
        AND p.post_type = 'product' AND p.post_status = 'publish' 
        AND tt.taxonomy = 'product_cat' AND t.slug = '%s'
    ", $term_slug ) );
}

代码位于子主题的functions.php 文件中(或插件中)。经过测试并可以工作。

使用示例显示“配件”产品类别术语别名的评论计数:

printf( 
    '<p class="reviews-count">'.__('Reviews count for %s category: %d', 'woocommerce').'<p>',
    __('Accessories', 'woocommerce'), 
    get_products_reviews_count_from_category( 'accessories' )
);

关于php - WooCommerce 统计给定产品类别的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77517080/

相关文章:

javascript - 在 PHP 中使用正则表达式按字母顺序对字母进行排序

php - 如何更新一个sql db

php - 如何在页面末尾加载javascript

php - 如何使 woo 产品 View 中的自定义列可排序?

wordpress - 对archive-product.php所做的更改不起作用

java - java中的Symfony FOSUser Hash算法

wordpress - get_posts 不返回多种帖子类型

php - 查看用户是否从 id 登录到 wordpress

javascript - ajax加载后调用函数?

javascript - 隐藏产品可变价格,直到在 WooCommerce 中选择所有变体字段