0

I would like to ask about the way to track the last item added on the cart. I don't want to switch the product I just want to track it and display it on the error handling of the Cart. How would I do it?

Note: I only allow a single product on cart and disregard the last item added if not same with the product on the cart.

2 Answers 2

1

Just two line code for that

$collection = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection();

echo $collection->getLastItem()->getName();

9
  • Thanks for the reply. The code works on an empty cart only.
    – Alen
    Commented Nov 20, 2015 at 5:28
  • Above code will display last added product name. If cart is empty then it will display nothing actually. Commented Nov 20, 2015 at 5:36
  • but when I got an item on the cart same product is being showed not the last added product.
    – Alen
    Commented Nov 20, 2015 at 5:38
  • Don't know why, but it should work in each case. Check once in private window. You could use that code in any phtml Commented Nov 20, 2015 at 5:55
  • I did use it and it is working but not just I wanted it to be,.
    – Alen
    Commented Nov 20, 2015 at 7:08
0

you can get the last item in the cart with below code

$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
            $last = 0;
            $lastItem = null;
            foreach ($items as $item){
                if ($item->getId() > $last) {
                    $last = $item->getId();
                    $lastItem = $item; 
$_product = $lastItem->getProduct();
                echo $xproductsku = $_product->getName();

                }
            }
            if ($lastItem){
                $_product = $lastItem->getProduct();
                echo $xproductsku = $_product->getName();

            }
 ?>
16
  • Can this be put on the .phtml code? I do think the product last added is being rejected by the Observer or Something. Sorry but I am new with Magento.
    – Alen
    Commented Nov 20, 2015 at 5:11
  • yes you can put in phtml. Commented Nov 20, 2015 at 5:12
  • 1
    I see. I will try is first. I will mark it solve when it is working on my site.
    – Alen
    Commented Nov 20, 2015 at 5:17
  • It is correct on the empty cart but not when I add a different product.
    – Alen
    Commented Nov 20, 2015 at 5:27
  • i test it is working on adding the product too. last product i added it's shows Commented Nov 20, 2015 at 5:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.