Tuesday, December 27

How to get product rating and review in Magento

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; ?>

Ref : http://blog.chapagain.com.np/magento-how-to-get-product-rating-and-review

No comments:

Post a Comment