All posts in Uncategorized

How To Sort Items in Magento’s Cart Page

If you want to sort the items that appear in the Cart page in Magento, you can use the following code to set any attribute as the sort for the item collection.


Inside the template’s cart page (template/checkout/cart.phtml) the code calls the block’s getItems() method and received an array of items that it iterates through and then calls getItemHtml() to render the item.

Digging into the Mage_Checkout_Block_Cart_Abstract class shows that the current Quote model (Mage_Sales_Model_Quote) method getAllVisibleItems() is called.

This method gets all items in the quote that are not deleted nor child items. Normally when working with collections in Magento you can use the method addAttributeToSort() as shown in the Magento wiki, but the Quote collection class (Mage_Sales_Model_Mysql4_Quote_Item_Collection) doesn’t implement that method.

It’s easy enough to instead use the method addOrder() in the Varien_Data_Collection_Db class to set an order on the collection.

The following code shows how this can be done in the cart.phtml file. I’d suggest putting this into a module that extends Mage_Sales_Model_Mysql4_Quote_Item_Collection for a better implementation.

The Code


[php]foreach($this->getItems() as $_item): [/php]
$cartitems = Mage::getModel(‘sales/quote_item’)->getCollection()
->addOrder(‘name’, ‘asc’);

$items = array();
foreach ($cartitems as $item) {
if (!$item->isDeleted() && !$item->getParentItemId()) {
$items[] = $item;


The above code gets the current cart items from the Quote, adds a field to the select (‘name’), and adds a sort based on that attribute (Either ASC or DESC).

Custom attributes can be added to the select and then sorted.