[英]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. 我正在尝试从外部php脚本中将产品添加到购物车。 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. 因此,请确保您拥有ID为1的产品并且数量足够。
I had try above code it work perfectly for me. 我已经尝试过上面的代码,它对我来说非常合适。
My folder structure is magento/test/test.php 我的文件夹结构是magento / test / test.php
Let me know if you have any query. 让我知道您是否有任何疑问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.