I got a list of categories that show on a product view page. The list is shown as a few top categories with their sub categories under them. This works, except it, now shows all the categories from my entire website, not only the categories, the current product belong too.
How can I fix that?
My code:
$categoryCollection = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('level',2)
->addAttributeToSelect('name')
->addAttributeToSelect('id')
// ->addFieldToFilter('id', array('nin' => 128))
->addAttributeToSelect('url');
$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')->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;
This shows ALL top categories from my website with ALL their subcategories.
I only want to show the categories that the product belong too.
I got it to work but this doesn't show them in the list style I want, it just shows them all in one big list, not sorted by their parent categories. (with this code:)
// Haal alle categorieen op waar het product onder valt
$currentCatIds = $_product->getCategoryIds();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToSelect('name')
->addAttributeToSelect('url')
->addAttributeToFilter('entity_id', $currentCatIds)
->addIsActiveFilter();
// echo '<pre>';
// print_r($categoryCollection);
// echo '</pre>';
$sorted = sort($categoryCollection);
$catlist .= '<ul class="categorielijst">';
foreach($categoryCollection as $cat){
if($cat->getName() != 'Root'){
$catlist .= '
<li><a href="'.$cat->getUrl().'">'.$cat->getName().'</a></li>';
}
}
$catlist .= '</ul>';
echo $catlist;