Magento – Magento 2 product review & rating

magento2product-viewratingsreview

In Magento 2 product view page I want to do following things…

  1. Check if product has 0 or more rating.
  2. Get an average rating of product rating wise

For e.g.

Price : 2.5/5.0

Quality : 4.5/ 5.0

Rating : 4.9/5.0

So far I got following

echo $block->getReviewsSummaryHtml($_product,"sort",true); 

From above I'm getting average rating but I want to extract more information from it like ratingValue and want more details…so how can I achieve that?

Best Answer

You can take the Magento 2 module-review as a reference. \vendor\magento\module-review\view\frontend\templates\form.phtml

<?php foreach ($block->getRatings() as $_rating):
       <?php $options = $_rating->getOptions();?>
       <?php $iterator = 1; foreach ($options as $_option):
             echo $_option->getValue()
             <?php $iterator++; ?>
             <?php endforeach; ?>
<?php endforeach; ?>

Observe the below block files and how the functions used in templates to get more details on Reviews and Ratings.

\vendor\magento\module-review\Block\Product\ReviewRenderer.php \vendor\magento\module-review\Block\View.php