Woocommerce 计算给定产品类别的评论

问题描述 投票:0回答:1

我需要显示特定类别中所有产品的评论计数。以下代码用于计算所有产品的所有评论(作为评论),但是 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;

}

}
php wordpress woocommerce review taxonomy-terms
1个回答
0
投票

您需要使用自定义的轻量级 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 文件中(或插件中)。已测试并工作。

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

printf( 
    '<p class="reviews-count">'.__('Reviews count for %s category: %d', 'woocommerce').'<p>',
    __('Accessories', 'woocommerce'), 
    get_products_reviews_count_from_category( 'accessories' )
);
© www.soinside.com 2019 - 2024. All rights reserved.