1

How to get the category products review count in category page and calculate the review stars?

1

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.

  1. Get all products of the category programmatically.
  2. Loop through the products and in the loop, get the ratings and number of reviews.
  3. Add up the number of reviews in the loop and assign it to a variable.
  4. 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.

| improve this answer | |
0

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 . '&nbsp;'; ?><span>Reviews</span></a></div></div><?php } ?>
| improve this answer | |
  • Hi tried above code, i got the error as "Fatal error: Uncaught Error: Call to undefined method Magento\Catalog\Model\Product\Type\Simple::getUsedProducts()". – Rat Jul 5 '18 at 12:25
  • $usedProducts fetching products id's for loop you can use your custom code for fetch product id – Jugal Kishor Jul 6 '18 at 5:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.