Ivar
Ivar

Reputation: 4392

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!

Upvotes: 6

Views: 18445

Answers (1)

Rajat Modi
Rajat Modi

Reputation: 1343

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.

Upvotes: 8

Related Questions