Magento – Sorting Product List by more than one attribute

catalogproduct-list

On my category page's normal listing of products, I have it set to sort the products by a custom yes/no attribute in the admin. This works fine, but I also want to sort it by SKU after it's sorted by the attribute. Here's my current code in catalog list.phtml:

$_productCollection=$this->getLoadedProductCollection();
foreach ($_productCollection as $_product):
    // do product stuff here
endforeach;

I've tried adding things like $_productCollection->setOrder('sku', 'ASC');, addOrder, addAttributeToSort, but none of them seem to actually affect the sort order of the products on the page. What am I missing?


Progress from comments following pzirkind's suggestion of https://stackoverflow.com/questions/5673093/sort-magento-collection-after-load :

$_productCollection=$this->getLoadedProductCollection();

$collectionReflection = new ReflectionObject($_productCollection);
$itemsPropertyReflection = $collectionReflection->getProperty('_items');
$itemsPropertyReflection->setAccessible(true); // Make it accessible

$collectionItems = $itemsPropertyReflection->getValue($_productCollection);

usort($collectionItems, $yourSortingCallback);

$itemsPropertyReflection->setValue($collectionItems, $collectionItems);

$itemsPropertyReflection->setAccessible(false);

There's a couple of issues with this, #1 being that I'm not sure how to get $collectionItems back into the collection… this doesn't do it by itself. If I print_r($collectionItems) it is now sorted by SKU, however the other problem is that the order is only for the products on that page, this sorting is NOT done before pagination is performed some how.


In order to get past the first problem, I tried a different approach and this DOES work. However, it's still only sorting by SKU AFTER pagination

$_productCollection=$this->getLoadedProductCollection()->clear()->addAttributeToSort('sku', 'ASC');

Best Answer

Did you try this

$Collection->setOrder(array('attribute1', 'attribute2'), asc);

Pass an array of attribute inside the setOrder().