0

I want a list of categories with under each categoryname their children categories. But my code isn't working, the top categories are showing but

<ul class="sub"></ul>

is empty, so the children are not showing.

This is my code:

$categoryCollection = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('level',2)
->addAttributeToSelect('name')
->addAttributeToSelect('url');
$out = "<ul>";
foreach($categoryCollection as $cat){
    $children = $cat->getChildren();
    $out .= "<li>";
    $out .= "<b><a href='".$cat->getUrl()."'>".$cat->getName()."</a></b>";
        $out .="<ul class='sub'>";
        foreach($children as $child){
            $ChildModel = Mage::getModel('catalog/category')->load($child)
            ->addAttributeToSelect('name');
            $out .="<li><a href='".$ChildModel->getUrl()."'>".$ChildModel->getName()."</a></li>";
        }
        $out .="</ul>";
    $out .= "</li>";
}
$out .= "</ul>";
echo $out;

1 Answer 1

0

Replace below code with your code:

$out .="<ul class='sub'>";
$children = Mage::getModel('catalog/category')->load($children->getId())->getChildrenCategories();

    foreach($children as $child){

        $out .="<li><a href='".$child->getUrl()."'>".$child->getName()."</a></li>";
    }
    $out .="</ul>";

Edit this line:

$children = Mage::getModel('catalog/category')->load($cat->getId())->getChildrenCategories();

[Edit]

You want show only current product parent categories? right?

click here

This may help you.

16
  • I get: Fatal error: Call to a member function getId() on string in
    – twan
    Commented Sep 5, 2017 at 13:36
  • I have edit answer please see Commented Sep 5, 2017 at 13:41
  • and remove $children = $cat->getChildren(); this line Commented Sep 5, 2017 at 13:41
  • it's working or not? if working then accept answer and give upvote. Commented Sep 5, 2017 at 13:45
  • It shows all sub-categories from that category, how can I get only the sub categories that the product is in? The list is shown on the product view page. Also it shows all topcategories, I only need the categories from the current product.
    – twan
    Commented Sep 5, 2017 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.