'WooCommerce: Get average rating from multiple products [duplicate]
I've a custom loop to get a list of products based on a list of product IDs. Now I try to get the total ratings and average rating of all the products within that loop.
The total count of ratings isn't the problem. My problem is that I don't get the star rating from the comments. (I'm using the plugin "WooCommerce Product Reviews Pro")
Here's my current loop so far:
<?php $args = array (
'post_type' => 'product',
'number' => '-1',
'post__in' => $product_ids,
'meta_key' => 'rating',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$comments = get_comments( $args );
echo count($comments);
?>
<?php if ( !empty($comments) ) : ?>
<pre><?php print_r($comments); ?></pre>
<?php foreach ( $comments as $comment ) {
echo $comment_ID = $comment->comment_ID;
} ?>
<?php endif; ?>
With echo count($comments) I get the total count of ratings.
But if I do print_r($comments), I don't see the star rating for the review.
I guess that I need to use the comment ID for that.
With the foreach I get all comment Ids as a string.
But I'm not sure where to look and how I add all ratings to generate a new average rating for the selected posts from the loop.
EDIT: I found another way to get to the average ratings. This time I loop through the posts instead the comments.
So I can get the average rating for every product.
The problem is that in that loop are also ratings with a 0 if there are no comments/reviews.
Here's the loop for the product so far:
$average_ratings = array();
foreach ( $posts as $post ) {
global $product;
echo $average_ratings[] = $product->get_average_rating();
}
var_dump($average_ratings);
Solution 1:[1]
I found an answer. This is my code:
<?php
$args = array (
'post_type' => 'product',
'post__in' => $product_ids,
'meta_key' => 'rating',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$comments = get_comments( $args );
$total_ratings = count($comments);
?>
<?php if ( !empty($comments) ) : ?>
<?php
$average_ratings = array();
foreach ( $comments as $comment ) {
$comment_post_ID = $comment->comment_post_ID;
$product = wc_get_product( $comment_post_ID );
$average_ratings[] = $product->get_average_rating();
}
$average_ratings = array_filter($average_ratings);
$average = array_sum($average_ratings)/count($average_ratings);
echo $average;
?>
<?php endif; ?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cray |
