如何以编程方式将子产品添加到购物车?
我有一个子产品SKU
,我想要
- 从产品中获取 super 属性例如
尺寸
和颜色ID
以及值, - 然后获取父
产品 ID
, - 在参数上传递 super 属性和数量,以添加到
功能购物车
。
//$cart->addProduct($product1, $options);
这里,如何将supper属性传递到$option
变量上?请帮助我!!!!
最佳答案
试试这个。我认为它可能需要一些改进,但在简单的情况下效果很好。
$_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();
}
关于Magento:以编程方式将可配置产品添加到购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27200449/