我的 Magento 网站上的一些产品具有自定义选项(不是属性)。对于一种产品,它有金色或银色可供选择,它有一个带有这两个选项的下拉菜单。如何获取用户选择显示在购物车页面上产品名称旁边的选项名称?
5 回答
要在“AddtoCart”时间设置的购物车页面获取产品自定义选项值,请尝试使用以下代码。
$cart = Mage::helper('checkout/cart')->getCart()->getQuote()->getAllItems();
/* cart item loop */
foreach($cart as $item) {
/* This will get custom option value of cart item */
$_customOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
/* Each custom option loop */
foreach($_customOptions['options'] as $_option){
echo $_option['label'] .'=>'. $_option['value']."<br/>";
// Do your further logic here
}
}
使用以下代码,您可以获得产品自定义选项值。
$productOptions= $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
If you choose to go with Mage_Catalog_Model_Product_Type_Configurable::getOrderOptions($product) as suggested by others, make sure you don't call it on disabled products as in version CE 1.9.* (possibly in other versions, too) this leads to a nasty function call on null. Unless you haven't added a custom module that purges disabled products from carts, this can make your site crash for every customer who added a later disabled product to their cart.
Luckily, you don't need to worry about that if you're using or extending Magento's cart item renderer Mage_Checkout_Block_Cart_Item_Renderer. It offers method getOptionList() which will return an array of all selected options to you, custom options included:
//$this = Mage_Checkout_Block_Cart_Item_Renderer
$options = $this->getOptionList();
This method getOptionList() calls Mage_Catalog_Helper_Product_Configuration which will be your answer if you're not using the Magento renderers or if you want a list of only custom options.
Here's an example of how you can get an array of the selected custom options by calling the helper directly:
$_item = $this->getItem(); // item can represent a simple, configurable or grouped product
$helper = Mage::helper('catalog/product_configuration');
if($onlyCustomOptions){
// get an array of only custom options
$options = $helper->getCustomOptions($_item);
} else {
// get an array of configurable & custom options
$options = $helper->getOptions($_item);
}
(Note: $options will be an empty array if the item has no options.)
如果不显示,那么你应该试试这个。
$product = Mage::getModel('catalog/product')->load($product_id);
$options = $product->getProductOptions();
foreach ($options as $option){ print_r($option->getValues()); }
你会发现期权价值
使用以下代码加载产品:
$product = Mage::getModel('catalog/product')->load($product_id);
然后通过以下方式获取自定义选项:
$options = $product->getProductOptions();
希望这有帮助,
逾越节