Question

I want to get a collection of all the items in cart currently.

How can I do this ? Any suggestions will be appreciated.

Was it helpful?

Solution

$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
    $productName = $item->getProduct()->getName();
    $productPrice = $item->getProduct()->getPrice();
}

in $cart you got all collection of cart item and if you want to get product id,name you can get from using foreach loop

OTHER TIPS

I found another solution. The following code works for me.

$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
    $productId = $item->getProductId();     
    // Do something more
}

There are several methods that work in a different way:

  1. $items = Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
    

    Returns a quote item collection with all items associated to the current quote.

  2. $items = Mage::getSingleton('checkout/cart')->getItems();
    

    This is a shortcut for the method above, but if there is no quote it returns an empty array, so you cannot rely on getting a collection instance.

  3. $items = Mage::getSingleton('checkout/cart')->getQuote()->getAllItems();
    

    Loads the item collection, then returns an array of all items which are not marked as deleted (i.e. have been removed in the current request)

  4. $items = Mage::getSingleton('checkout/cart')->getQuote()->getAllVisibleItems();
    

    Loads the item collection, then returns an array of all items which are not marked as deleted AND do not have a parent (i.e. you get items for bundled and configurable products but not their associated children). Each array item corresponds to a displayed row in the cart page.

Choose what fits your needs best. In most cases the last method is what you need, but unfortunately Magento only provides it as array and not as collection.


Note that Mage::getSingleton('checkout/cart')->getQuote() and Mage::getSingleton('checkout/session')->getQuote() are interchangable.

$items =Mage::getSingleton('checkout/session')->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}

best way to get the all item in cart

Below code is used for getting cart items

$cart = new Mage_Checkout_Model_Cart();

$cart->init();

foreach ($cart->getItems() as $item) {

   // we can wrap our request in this IF statement

   if (!$item->getParentItemId()) {

   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top