How to get the category products review count in category page and calculate the review stars?
2 Answers
At the time of writing the answer, you have not shared the Magento version. So below is the theoretical answer which will work for Magento 1.x as well as Magento 2.x both.
- Get all products of the category programmatically.
- Loop through the products and in the loop, get the ratings and number of reviews.
- Add up the number of reviews in the loop and assign it to a variable.
- Add up rating value and calculate the average of all ratings. Assign it to a different variable.
Use the variables mentioned in step #3 and step #4 to show the data you wanted in the question.
Use Your Model instead of this line for get product id
$usedProducts = $productTypeInstance->getUsedProducts($_product);
Because this was getting id from configurable product
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$ratingModel = $objectManager->create('Magento\Review\Model\Rating');
$productTypeInstance = $_product->getTypeInstance();
$usedProducts = $productTypeInstance->getUsedProducts($_product);
$ratings = array();
$reviewCount = array();
foreach ($usedProducts as $child) {
$RatingOb = $ratingModel->getEntitySummary($child->getId());
if (!empty($block->getReviewsSummaryHtml($child))) {
$ratingsGet = ($RatingOb->getSum() / $RatingOb->getCount());
$ratings[] = $ratingsGet;
$reviewCount[] = $RatingOb->getCount();
}
}
if (!empty($reviewCount)) {
$getReviewCount = array_sum($reviewCount);
}
if (!empty($getReviewCount)) {
$totalReviewCount = ($getReviewCount / 3);
}
if (!empty($ratings)) {
$totalAvarageRating = (array_sum($ratings) / count($ratings));
}
?>
<?php if (!empty($totalAvarageRating) && !empty($totalReviewCount)) {
?>
<div class="product-reviews-summary short">
<div class="rating-summary">
<span class="label"><span>Rating:</span></span>
<div class="rating-result" title="<?php echo $totalAvarageRating . '%'; ?>">
<span style="width:<?php echo $totalAvarageRating . '%'; ?>">
<span><?php echo $totalAvarageRating . '%'; ?></span>
</span></div></div><div class="reviews-actions"><a class="action view" href="<?php echo $_product->getProductUrl(); ?>#reviews"><?php echo $totalReviewCount . ' '; ?><span>Reviews</span></a></div></div><?php } ?>
-
Hi tried above code, i got the error as "Fatal error: Uncaught Error: Call to undefined method Magento\Catalog\Model\Product\Type\Simple::getUsedProducts()".– RatJul 5, 2018 at 12:25
-
$usedProducts fetching products id's for loop you can use your custom code for fetch product id Jul 6, 2018 at 5:09