I want to show a list of categories a product belongs to, top categories and subcategories.
I figured out how to load the correct topcategories, but when I loop the subcats (children categories) it loads ALL subcats of that topcategory, not the categories that the product falls under.
Example:
Like you can see it loads a ton of subcategories, but only the ones with the red stripe are subcategories that the product falls under.
How can I make sure it only show those under their topcategories?
My code:
$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;
2
Answers
In your loop check if category has product or not.
if($cat->getProductCount()){..}
and same thing for$child
Please try my code, It will work.