Magento: How to get top rated products?

Here, I will be showing you how to get the top/highest rated product.

The basic idea for getting the top rated products is fetching all products, looping through them, getting ratings of each product and populating a ratings array. After that sort the array and then slice the array for limiting the number of product to display.

Here is the function to get the top rated products:-


/**
 * Get Top Rated Products
 *
 * @return array
 */
public function getTopRatedProduct() { 

	$limit = 5; 

	// get all visible products
	$_products = Mage::getModel('catalog/product')->getCollection(); 
	$_products->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
	$_products->addAttributeToSelect('*')->addStoreFilter();            
		
	$_rating = array(); 

	foreach($_products as $_product) {  
	
		$storeId = Mage::app()->getStore()->getId(); 

		// get ratings for individual product
		$_productRating = Mage::getModel('review/review_summary') 
							->setStoreId($storeId) 
							->load($_product->getId()); 
		 
		$_rating[] = array(
					 'rating' => $_productRating['rating_summary'], 
					 'product' => $_product                         
					);  			
	} 

	// sort in descending order of rating
	arsort($_rating); 
	
	// returning limited number of products and ratings
	return array_slice($_rating, 0, $limit); 
}

Now, you can display the products in any template file. Here is the sample code to display the top rated products:-


<!-- I suppose that you have put the getTopRatedProduct() function in helper class of your module -->
<?php $topRatedProducts = $this->helper('yourModule')->getTopRatedProduct();?>

<ul>
<?php foreach($topRatedProducts as $_rating): ?>
	<?php $_product = $_rating['product']; ?>
<li>			
	<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(150); ?>"  alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
	<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">	
		<span>View Details</span>
	</a>
</li>
</ul>
<?php endforeach; ?>

Hope this helps. Thanks.