如何以编程方式在Magento中获取可汇总的属性和选项
-
13-12-2019 - |
题
我想要类别的可过滤属性及其选项,因此我使用以下代码
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($category_id);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
foreach($attributes as $attribute){
if($attribute->getAttributeCode() == 'price'){
$filterBlockName = 'catalog/layer_filter_price';
}elseif($attribute->getBackendType() == 'decimal'){
$filterBlockName = 'catalog/layer_filter_decimal';
}else{
$filterBlockName = 'catalog/layer_filter_attribute';
}
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();
$count = count($result->getItems());
if($count > 0){
$attribute->getFrontendLabel();
$attribute->getAttributeCode();
}
if($count > 0){
foreach($result->getItems() as $option) {
$option->getLabel();
$option->getValue();
}
}
}
.
现在我得到了正确的输出。例如,我正在进行输出
brand - HP,Dell
processer - i3,i5,i7
.
现在问题是当我应用一个名为处理器i7的过滤器时,我只有一个名为Dell的产品,所以一个戴尔产品被正确显示,但我需要默认属性如下
brand - Dell
processer - i3,i5,i7
.
我得到的是惠普和戴尔。这是编程方式我正在做。我需要层叠导航在Magento类别清单页面中的方式。
解决方案
我用以下代码做了自己,只是分享对这里的其他人有所帮助的代码
$categoryId = '5'; // replace with your category id here
$category = Mage::getModel("catalog/category")->load($categoryId);
$layer = Mage::getModel("catalog/layer");
$layer->setCurrentCategory($category);
$setIds = Mage::getModel('eav/entity_attribute_set')
->load($attrSetName, 'attribute_set_name')
->getAttributeSetId();
$attributes = Mage::getResourceModel('catalog/product_attribute_collection');
$attributes->setItemObjectClass('catalog/resource_eav_attribute')
->setAttributeSetFilter($setIds)
->addStoreLabel(Mage::app()->getStore()->getId())
->setOrder('position', 'ASC');
$attributes->addFieldToFilter('additional_table.is_filterable', array('gt' => 0));
$attributes->load();
foreach ($attributes as $attribute) {
$filter_attr = array();
$filter_attr['title'] = $attribute->getFrontendLabel();
$filter_attr['code'] = $attribute->getAttributeCode();
if ($attribute->getAttributeCode() == 'price') {
$filterBlockName = 'catalog/layer_filter_price';
}elseif ($attribute->getBackendType() == 'decimal') {
$filterBlockName = 'catalog/layer_filter_decimal';
}else {
$filterBlockName = 'catalog/layer_filter_attribute';
}
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();
$i=0;
foreach($result->getItems() as $option) {
$attr_option = array();
if($attribute->getAttributeCode() == 'price') {
$attr_option['label'] = str_replace(array('<span class="price">','</span>'),'',$option->getLabel());
} else {
$attr_option['label'] = $option->getLabel();
}
$attr_option['value'] = $option->getValue();
$attr_option['count'] = $option->getCount();
$i++;
$filter_attr['options'][] = $attr_option;
}
if($i!=0){
$filter_attributes[] = $filter_attr;
}
}
.