Sort Products by review count in Magento

The product collection in magento can be sorted by the direct product attributes like name, price, sku, created time, etc., by the following way.

$productCollection->addAttributeToSort(‘name’, ‘desc’);

If you want to sort a product collection by the number of review the product has received, there raises the complexity.

Because, ‘reviews_count’ is a attribute available in RatingSummary class and it is not directly related to Product Collection. So to sort products by their reviews count. We need to traverse the collection and obtain the reviews_count attribute from the RatingSummary class and add it directly to the product collection. Following is the snippet for performing the above mentioned task.

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
$newarray = array();
foreach ($this->_productCollection as $product){
    $rating_summary = $product->getRatingSummary();
    if($rating_summary != null){
        $reviews_count = $rating_summary->getReviewsCount();
        $newarray[$product->getId()] = $reviews_count; 
    } else {
        $newarray[$product->getId()] = "0";
    }
}
if(is_array($newarray) && count($newarray) > 1){
    if ($sortDirection == 'asc') {
        arsort($newarray);
    } elseif ($sortDirection == 'desc') {
        asort($newarray);
    }
    $merged = $this->_productCollection; 
    foreach($newarray as $k => $v) {
        $item = $this->_productCollection->getItemById($k);
        if (!$merged->getItemById($item->getEntityId())) {
            $merged->addItem($item);
        }
    }
    $this->_productCollection = $merged;
}

here the ‘$sortDirection’ variable carries the value in which way you need the products to be sorted. And finally at the end of the code you will get the product collection sorted by its number of reviews for each product.

happy Coding!! :)

  • flamefox

    Great article, thanks! However, it must hard to add many additional sorting options, right? Is it better to use an extension for that? For example, I found this one https://amasty.com/improved-sorting.html