1

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);

2 Answers 2

4

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();
0

To get quote id and quote's item id, you can get using below code.

$currentcart = Mage::getModel('checkout/cart');
$quote = $currentcart->getQuote();
$quoteItemId = $quote->getEntityId();

To get quote's item id

$quoteItems = $quote->getAllVisibleItems();
foreach ($quoteItems as $item) {
    $ItemId = $item->getId();
}
0

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.