WooCommerce Count Reviews for a Given Product Category

58 views Asked by At

I need to display a review count for all products in a specific category. The following code works to count all reviews (as comments) for all products, however get_comments() doesn't seem to be set up to allow taxonomy queries...

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;
}
1

There are 1 answers

0
LoicTheAztec On BEST ANSWER

You need to use a custom lightweight SQL query. I have embedded that Sql query in the function below, with an argument: the product category term slug.

The function:

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 ) );
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and work.

Usage example displaying the reviews count for "accessories" product category term slug:

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