Programmatically adding product to cart returns empty cart
-
11-10-2020 - |
Frage
I'm trying to add a product to cart programmatically in magento 1.9.3.3. The code adds database entries (created rows in sales_flat_quote_item
and sales_flat_quote
tables). But the cart shows as empty.
Here is my code
$cart = Mage::getSingleton('checkout/session')->getQuote();
$product = Mage::getModel('catalog/product')->load(1);
$cart->addProduct($product,1);
$cart->save();
Mage::getSingleton('customer/session')->setCartWasUpdated(true);
Mage::getSingleton('core/session')->addSuccess('The product has been added to cart');
$this->_redirect('checkout/cart');
Lösung
<?php
include 'app/Mage.php';
Mage::app();
ini_set('display_errors', 1);
Mage::getSingleton('core/session', array('name' => 'frontend'));
try {
$product_id = '394'; // Replace id with your product id
$qty = '1'; // Replace qty with your qty
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
Mage::getSingleton('core/session')->addSuccess('Product added successfully');
header('Location: ' . 'checkout/cart/');
} catch (Exception $e) {
echo $e->getMessage();
}
?>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange