Magento 1.9 Add to Cart – Get Item ID After Programmatically Adding Product to Cart

addtocartcartmagento-1.9productquoteitem

I want to add a product programmatically to the cart. My product is added by using the following code. But it didn't return the quote item id. How can I get the item id? Here is my code

$id = 100;
$qty = '2'; 
$_product = Mage::getModel('catalog/product')->load($id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Best Answer

Your code can be further simplified using the quote's addProduct method:

$id = 100;
$qty = 2;
$product = Mage::getModel('catalog/product')->load($id);
$quote = Mage::getSingleton('checkout/session')->getQuote();

//Returns the newly created quote item or an error
$quoteItem = $quote->addProduct($product, $qty);

//Collect totals and save the quote
$quote->collectTotals()->save();

//Grab the id from the new quote item
echo $quoteItem->getId();
Related Topic