简体   繁体   中英

magento 1.9 add product to cart not working from an external URL

I'm trying to add a product to cart from an external php script. following is the code, but it's not adding the product to the cart.

require_once '../app/Mage.php';
Mage::init();

$id = '2'; // product id
$qty = '1'; // qty

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

any suggestions will be appreciated.

Thanks

Please try the below code

 <?php include '../app/Mage.php'; Mage::app(); // Need for start the session Mage::getSingleton('core/session', array('name' => 'frontend')); try { $product_id = '1'; // Replace id with your product id $qty = '1'; // Replace qty with your qty $product = Mage::getModel('catalog/product')->load($product_id); $cart = Mage::getSingleton('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: ' . '../index.php/checkout/cart/'); } catch (Exception $e) { echo $e->getMessage(); } ?> 

All so make sure that you have product with id 1 exists and also enough quantity.

I had try above code it work perfectly for me.

My folder structure is magento/test/test.php

Let me know if you have any query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM