6

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!

Ivar
  • 4,344
  • 6
  • 38
  • 53
  • 2
    possible duplicate of [Magento - load only configurable products](http://stackoverflow.com/questions/5280392/magento-load-only-configurable-products) – clockworkgeek Nov 30 '11 at 19:32
  • No dublicate; that question is about performance, this question is about sorting. – Ivar Nov 30 '11 at 19:48
  • 4
    I shouldn't have used the default "duplicate" message, it was misleading. I meant to show that `getLoadedProductCollection` gets a collection that is already loaded and needs to be reset before you can adjust the sort order (or filter). – clockworkgeek Nov 30 '11 at 19:55
  • Feels like a dirty solution, but it works - thank you for the tip! – Ivar Nov 30 '11 at 20:26
  • I guess loaded product collection means that collection is already loaded (query to db was already run) at this point. That's why you can't reorder already loaded collection. – Dmytro Zavalkin Nov 30 '11 at 20:29

1 Answers1

8

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.

user487772
  • 8,800
  • 5
  • 47
  • 72
Rajat Modi
  • 1,343
  • 14
  • 38