All about Magento E-commerce Store.......MagentoForum: Magento: How to get product rating and review?

Sunday, January 8, 2012

Magento: How to get product rating and review?


Here is the code to get ratings and reviews for any particular product.
/**
 * Getting reviews collection object
 */
$productId = $product->getId();
$reviews = Mage::getModel('review/review')
    ->getResourceCollection()
    ->addStoreFilter(Mage::app()->getStore()->getId())
    ->addEntityFilter('product', $productId)
    ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
    ->setDateOrder()
    ->addRateVotes();
/**
 * Getting average of ratings/reviews
 */
$avg = 0;
$ratings = array();
if (count($reviews) > 0) {
 foreach ($reviews->getItems() as $review) {
  foreach( $review->getRatingVotes() as $vote ) {
   $ratings[] = $vote->getPercent();
  }
 }
 $avg = array_sum($ratings)/count($ratings);
}
Displaying the ratings
<!-- REMOVE 'IF CONDITION', TO SHOW RATING IN ALL RATED/UNRATED PRODUCTS -->
<?php if($avg): ?>
 <div class="rating-box" style="float:left;">
  <div class="rating" style="width: <?php echo ceil($avg) ; ?>%;"></div>
 </div>
<?php endif; ?>

Hope this helps. Thanks.

No comments:

Post a Comment