我遇到了Magento的addProduct()函数问题。我有以下代码:
<?php
// Mage init
include_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 with custom options
$productId = 11348;
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productInstance->getId(),
'qty' => 1,
'options' => array(
528 => '1756', // Custom option with id: 528
527 => '1753', // Custom option with id: 527
526 => '1751' // Custom option with id: 526
)
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
// update session
$session->setCartWasUpdated(true);
// save the cart
$cart->save();
?>
它昨天工作,所以包括和$ param是严格的,但现在它不起作用。 您也可以将此产品添加到商店内的购物车中,以便产品存在且有库存。 此代码似乎没有任何错误,但它没有将产品添加到购物车。
感谢您的帮助。
答案 0 :(得分:1)
<?php
require_once('app/Mage.php');
umask(0);
Mage::app('admin');
$product_model = Mage::getModel('catalog/product');
$my_product_sku = 'test';
$my_product_id = $product_model->getIdBySku($my_product_sku);
$my_product = $product_model->load($my_product_id);
$qty_value = 13;
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($my_product, array('qty' => $qty_value));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
?>
答案 1 :(得分:0)
尝试添加form key
和uenc
字段
$param = array(
'product' => $productInstance->getId(),
'form_key'=>$form_key_put_here,
'uenc' =>Mage::app()->getRequest()->getParam('uenc', 1),
'qty' => 1,
'options' => array(
528 => '1756', // Custom option with id: 528
527 => '1753', // Custom option with id: 527
526 => '1751' // Custom option with id: 526
));
希望这会有所帮助。