A place to log my programming solutions.
8
Sep 09

Magento Clear Shopping Cart and Session

If you ever need to programmatically clear Magento’s shopping cart, use the snippet of code below. If you need to clear the user’s entire session, including the shopping cart, shipping information, billing information and chosen payment methods, please refer to the snippet further below.

Clear shopping cart

foreach( Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item ){
    Mage::getSingleton('checkout/cart')->removeItem( $item->getId() )->save();
}

Clear entire session

Mage::getSingleton(‘checkout/session’)->clear();

Happy coding!

  • StumbleUpon
  • Digg

Responses

  1. “Clear shopping cart” works perfectly.
    Thx!

  2. Chris

    What page should we update in order to get this working correctly? I figured out how to do it by modifying core code but was thinking someone was able to do it by modifying a design file.

  3. Atomschinken

    Shouldn’t do “Mage::getSingleton(‘checkout/cart’)->truncate();”

    the same?

  4. Eric

    Is there anyways to clear selected shipping method only. I want to clear everything that user selected (billing, shipping, shipping method info,…) when he click on “View Cart” link.

  5. Yes, please answer where is the file/location where you place this code snippet?

  6. David

    You’ll get much better performance if you rewrite the Empty Cart code as follows:


    $cart = Mage::getSingleton('checkout/cart');
    foreach( Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item ){
    $cart->removeItem( $item->getId() );
    }
    $cart->save();

  7. pierre j

    Your piece of code is exactly what I need, thanks. Customers are coming back and buying items that are no longer in inventory, but I believe because they are already in the carts Magento does not go back and insure they are still available and next thing I know I have another order for an out of stock items.

    My question is the same as Kristy’s, where exactly do I put this piece of code?

    all the best,
    pierre

  8. Hello,

    I am looking for a code to:
    - append or add new values in cart session
    - how to overwrite total in cart session as we need to change total of cart to a different value than the one set on back end (custom programing done on products)

    Basically i need to overwrite the cart session

    Thanks for letting me know if anyone has an answer, this is really urgent need.

  9. Arturo Hernandez

    @pierre

    You ay have thougth about it already. Put it in the logon. I have the same issue and I will try that.

  10. Avtar

    Thanks, Your code worked fine.

  11. Anil

    you can find the solution here for the php also

    http://phptalks.wordpress.com/

Leave a Response

About NVNCBL and Myself

Contact Me