magento 1.8 add product to cart using php
18,168
Had a fresh look at it and got it working nicely right away. Just for anyone's reference, here's the code I'm using (Magento 1.8):
// Mage init
require_once '../../app/Mage.php';
umask(0);
Mage::init('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
// Get customer session
$session = Mage::getSingleton('customer/session');
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product (simple); id:12, qty: 3
$cart->addProduct(12, 3);
// Add a product with custom options
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productInstance->getId(),
'qty' => 1,
'options' => array(
234 => 'A value' // Custom option with id: 234
)
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
// Set shipping method
$quote = $cart->getQuote();
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setShippingMethod('flatrate_flatrate')->save();
// update session
$session->setCartWasUpdated(true);
// save the cart
$cart->save();
Author by
Wilbert van de Ridder
Updated on June 04, 2022Comments
-
Wilbert van de Ridder almost 2 years
Up until Magento 1.7 I was able to use the following code to add a product to cart programatically:
require_once '../app/Mage.php'; Mage::getSingleton('core/session', array('name' => 'frontend')); umask(0); Mage::app(); $session = Mage::getSingleton('customer/session'); $product = Mage::getModel('catalog/product')->load(99); // Random product ID // get cart and add product $cart = Mage::getSingleton('checkout/cart'); $cart->init(); $cart->addProduct($product, 1); // update session $session->setCartWasUpdated(true); // save the cart $cart->save();
However, this does not work anymore in Magento 1.8. I've been trying/searching all day why this is the case. Sadly I haven't found any clue regarding this issue.
It may have to do with the changes in 1.8 which also causes the requirement for a form-key when using the URL method; this is a wild guess though.
Anyone any idea or a working example on how to do this when working with Magento 1.8?
-
mahdi over 9 yearshow about configurable product ? how do you add configurable product to cart ?
-
Wilbert van de Ridder over 9 years@mahdi: Iirc, that's exactly what the // Add a product with custom options part is about. A configurable product has a set of required options you will have to provide.
-
mkutyba over 9 yearsExcept a configurable product has
super_attribute
notoptions
-
Pushpendra almost 9 yearsWIthout
Mage::init('default');
my code through The product could not be found. Why? without this my code is not working while most of the documentation is without this line. Please tag my name while giving answer to notify me. -
nano about 8 yearsAnd how can you fetch that custom array ($param) in the cart page? foreach($cart->getItemsCollection() as $_item.... ?