我想要显示产品所属的类别列表,顶级类别和子类别。
我知道如何加载正确的topcategories,但当我循环子类别(子类别)时,它会加载该topcategory的所有子类别,而不是产品所属的类别。
示例:

就像你可以看到的那样,它加载了大量的子类别,但只有带有红色条纹的子类别才是产品所属的子类别。
我如何才能确保它只显示那些在它们的How类别下的内容?
我的代码:
$currentCatIds = $_product->getCategoryIds();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToSelect('name')
// ->addFieldToFilter('level',2)
->addAttributeToSelect('url')
->addAttributeToFilter('entity_id', $currentCatIds)
->addIsActiveFilter();
$out = "<ul>";
foreach($categoryCollection as $cat){
$out .= "<li>";
$out .= "<b><a href='".$cat->getUrl()."'>".$cat->getName()."</a></b>";
$out .="<ul class='sub'>";
$children = Mage::getModel('catalog/category')
// ->addAttributeToFilter('entity_id', $cat->getCategoryIds())
->load($cat->getId())
->getChildrenCategories();
foreach($children as $child){
$out .="<li><a href='".$child->getUrl()."'>".$child->getName()."</a></li>";
}
$out .="</ul>";
$out .= "</li>";
}
$out .= "</ul>";
echo $out;发布于 2017-09-30 00:31:20
在你的循环中,检查类别是否有product。$child的if($cat->getProductCount()){..}和同样的事情
$currentCatIds = $_product->getCategoryIds();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToSelect('name')
// ->addFieldToFilter('level',2)
->addAttributeToSelect('url')
->addAttributeToFilter('entity_id', $currentCatIds)
->addIsActiveFilter();
$out = "<ul>";
foreach($categoryCollection as $cat){
if($cat->getProductCount()){
$out .= "<li>";
$out .= "<b><a href='".$cat->getUrl()."'>".$cat->getName()."</a></b>";
$out .="<ul class='sub'>";
$children = Mage::getModel('catalog/category')
// ->addAttributeToFilter('entity_id', $cat->getCategoryIds())
->load($cat->getId())
->getChildrenCategories();
foreach($children as $child){
if($child->getProductCount()){
$out .="<li><a href='".$child->getUrl()."'>".$child->getName()."</a></li>";
}
}
$out .="</ul>";
$out .= "</li>";
}
}
$out .= "</ul>";
echo $out;发布于 2017-10-02 20:38:35
请尝试我的代码,它会工作的。
<?php
$currentCatIds = $_product->getCategoryIds();
foreach ($currentCatIds as $categoryid) {
$sub_categories = Mage::getModel('catalog/category')->load($categoryid)->getChildrenCategories();
foreach ($sub_categories as $category) {
$cat_details = Mage::getModel('catalog/category')->load($category->getId());
?>
<div class="col-sm-15 col-xs-4">
<div class="catImage">
<a href="<?php echo $cat_details->getUrl(); ?>" title="<?php echo $cat_details->getName(); ?>">
<img src="<?php echo Mage::getBaseUrl('media', array('_secure' => true)) . 'catalog/category/' . $cat_details->getThumbnail(); ?>" alt="<?php echo $cat_details->getName(); ?>"/>
</a>
</div>
<div class="title">
<a href="<?php echo $cat_details->getUrl(); ?>" title="<?php echo $cat_details->getName(); ?>"><?php echo $cat_details->getName(); ?></a>
</div>
</div>
<?php
}
}
?>https://stackoverflow.com/questions/46489302
复制相似问题