1

When I try to add the product to cart programmatically then give an error

The product could not be found.

Here is my code for product add to cart programmatically.

$productId = 2783;
$cart = Mage::getSingleton('checkout/cart');
$params = array('product' => $productId ,'qty' => 1);
$product = Mage::getModel('catalog/product')
        ->setStoreId(Mage::app()->getStore()->getId())
        ->load($productId);
print_r($product->getId());
$cart->addProduct($product,$params);
$cart->save();
$session = Mage::getSingleton('checkout/session');
$session->setCartWasUpdated(true);
2
  • is your product is Configurable Product? Or product with options? – Sumit Aug 29 '19 at 5:44
  • Simple product with no option – Chirag Gondaliya Aug 29 '19 at 5:46
1

You can use the below code to add a product to the cart programmatically.

Simple product with out options

$prod_id = 2783; // pass product id
$_product = Mage::getModel('catalog/product')->load($prod_id);
$params = array(
   'product' => $prod_id,
   'qty' => 1,
   'form_key' => Mage::getSingleton('core/session')->getFormKey()
);

$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, $params);
$cart->save();

$quote = Mage::getModel('checkout/session')->getQuote();
$quote->collectTotals()->save();

Simple product with options

$productId = "Your Product Id"
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$options = array('92'=>'49','144'=>'21');
$product = Mage::getModel('catalog/product')->load($productId);

$paramater = array('product' => $productId,
                    'qty' => '1',
                    'form_key' => Mage::getSingleton('core/session')->getFormKey(),
                    'options' => $options 
            );       

$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();

Configurable product

$productId = "Your Product Id"
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$options = array('92'=>'49','144'=>'21');
$product = Mage::getModel('catalog/product')->load($productId);

$paramater = array('product' => $productId,
                    'qty' => '1',
                    'form_key' => Mage::getSingleton('core/session')->getFormKey(),
                    'supper_attribute' => $options 
            );       

$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();

Hope it helps!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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