Retrieve top rated products in Magento

Here you learn how to display top rated products using an helper function and a snippet of a .phtml block.

This is the function you need to put in your helper ( mine is named ‘heart’, you’ll see that later ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php

public function getTopRatedProducts($limit) {

        $limit = (int) $limit;

        // retrieve all the products
        $products = Mage::getModel('catalog/product')->getCollection();

        $rated = array();

        foreach($products as $product) {

            $_product = Mage::getModel('catalog/product')
                        ->load($product->getid());

            $storeId    = Mage::app()->getStore()->getId();

            // retrieve reviews data related to the current products
            // of the iteration
            $summaryData = Mage::getModel('review/review_summary')
            ->setStoreId($storeId)
            ->load($_product->getId());

            // put a subarray containing name, url and rating of the
            // product in our array containing the products
            $rated[] = array(
                         'rating' => $summaryData['rating_summary'],
                         'name' => $_product->getName(),
                         'url' => $_product->getUrlPath()
                        );
        }

        // tell that the product's array must be ordered by rating DESC
        arsort($rated);

        // return the array with the amount of products defined by $limit
        return array_slice($rated, 0, $limit);
    }

So now that you are able to retrieve the products you need to put them in your Magento pages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php

//create the array of top rated products calling our function
$products = Mage::helper('heart')->getTopRatedProducts(5);

    foreach($products as $product){

        echo "
            <li>
                <a href='{$product['url']}' />
                    {$product['name']}
                </a>
            </li>
        ";
    }

That’s it!


Hi there! I recently wrote an ebook on web application security, currently sold on leanpub, the Amazon Kindle store and gumroad.

It contains 160+ pages of content dedicated to securing web applications and improving your security awareness when building web apps, with chapters ranging from explaining how to secure HTTP cookies with the right flags to understanding why it is important to consider joining a bug bounty program.

Feel free to skim through some of the free chapters published on this blog and, if the content seems interesting enough to you, grab a copy on leanpub, the Amazon Kindle store, gumroad or simply checkout right down below!

Buy the Web Application Security ebook for $6.99

In the mood for some more reading?

...or check the archives.