如何以编程方式将子产品添加到购物车?
我有一个儿童产品SKU
,我想
size
和color id
以及产品中的值,product id
,function cart
。 //$cart->addProduct($product1, $options);
这里,如何在$option
变量上传递supper属性?请帮帮我!!!!
答案 0 :(得分:4)
试试这个。我认为它可能需要一些改进,但在简单的情况下效果很好。
$_product = $this->getProduct();
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
// check if something is returned
if (!empty(array_filter($parentIds))) {
$pid = $parentIds[0];
// Collect options applicable to the configurable product
$configurableProduct = Mage::getModel('catalog/product')->load($pid);
$productAttributeOptions = $configurableProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($configurableProduct);
$options = array();
foreach ($productAttributeOptions as $productAttribute) {
$allValues = array_column($productAttribute['values'], 'value_index');
$currentProductValue = $_product->getData($productAttribute['attribute_code']);
if (in_array($currentProductValue, $allValues)) {
$options[$productAttribute['attribute_id']] = $currentProductValue;
}
}
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product with custom options
$params = array(
'product' => $configurableProduct->getId(),
'qty' => 1,
'super_attribute' => $options
);
$request = new Varien_Object();
$request->setData($params);
$cart->addProduct($configurableProduct, $request);
$session = Mage::getSingleton('customer/session');
$session->setCartWasUpdated(true);
$cart->save();
}
答案 1 :(得分:0)
你可以试试。
$cart = Mage::getModel('checkout/cart');
$cart->init();
$productCollection = Mage::getModel('catalog/product')->load($productId);
$cart->addProduct($productCollection ,
array( 'product_id' => $productId,
'qty' => 1,
'options' => array( $optionId => $optionValue));
$cart->save();