Get Cart Quantity in Magento

You can get the number of items currently in the cart using the following code.

$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
echo (int)$cart['items_qty'];

However,if the cart is empty, writing only the above code will show error (Because $cart[‘items_qty’] is only set when there are items on the cart). For that you need to check if the value is set or not. Hence the total code will be like –

$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
if(isset($cart['items_qty'])){
echo (int)$cart['items_qty'];
} else {
echo '0';
}

12 comments

  1. PS – it throws an error when the cart is empty (because 'items'qty' is not set then), therefore I encapsulated it within a function:

    function getCartQuantity () {
    $cart = Mage::getModel('checkout/cart')->getQuote()->getData();
    if (isset($cart['items_qty']))
    return (int)$cart['items_qty'];
    else
    return 0;
    }

    Echo like this:
    echo getCartQuantity ();

  2. Thanks eXe for pointing out the blank cart error and nice to know this post helped you. I have updated the post.

  3. I had bugs after the cart uncookied my items. The solution turned out to be using this if test:

    if (isset($cart['items_qty']) && $cart['items_qty'] > 0) {

    The "isset" will check to see if the value is null / empty, which is what throws the error.

  4. tmacedo-> If you need the total amount try this:
    echo Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal());
    Then you can format that number as you like

  5. Has anyone experienced any problems when using Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() to return items in the cart. I have a problem whereby if a customer leaves items in the cart and logs out and I then change that item in the backend the customer cannot log back in until I reset their account in admin. The problem seems to lie with some custom tier pricing code that uses Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() to pull items out of the cart. Any suggestions or ideas as to what might be happening would be cool!

  6. Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal()); – will return you totla card+tax+shipping

    if you need each value of price you can read from:

    Mage::getModel('checkout/cart')->getQuote()->getData(); — will return you array of each price

Leave a comment

Your email address will not be published. Required fields are marked *