Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento: Sorting a product collection

I'm creating a template to display featured products on the home page, and I'd like to control the order of the products.

This is what I'm using at the moment to fetch a product collection based on a category:

<?php
    $_productCollection = $this->getLoadedProductCollection();
?>

No specific sorting at all.

When I were going to sort the products, I expected this to work:

<?php
    $_productCollection = $this->getLoadedProductCollection()->addAttributeToSort('name', 'ASC');
?>

But there's no difference at all. What am I doing wrong?

Thank you in advance!

like image 656
Ivar Avatar asked Nov 30 '11 19:11

Ivar


1 Answers

use this one I have worked on the same way try it.

$collection = Mage::getModel('catalog/product')
             ->getCollection()
             ->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_ASC);

for descending order:

$collection = Mage::getModel('catalog/product')
              ->getCollection()
              ->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_DESC);

for product with its category:

$collection = Mage::getModel('catalog/category')->load($categoryId)
             ->getProductCollection()
             ->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_ASC);

Or you can find more help on magento wiki.

like image 134
Rajat Modi Avatar answered Nov 14 '22 07:11

Rajat Modi