Question

With the code below I try to get the children categories from a specific parent category with ID 7.

<?php
    $rootCatId = Mage::app()->getStore()->getRootCategoryId();

    function getTreeCategories($parentId, $isChild){
        $allCats = Mage::getModel('catalog/category')->getCollection()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('is_active','1')
                    ->addAttributeToFilter('include_in_menu','1')
                    ->addAttributeToFilter('parent_id',array('eq' => $parentId));

        $class = ($isChild) ? "sub-cat-list" : "cat-list";
        $html .= '<ul class="'.$class.'">';
        $children = Mage::getModel('catalog/category')->getCategories(7);
        foreach ($children as $category) {
        {
            $html .= '<li>'.$category->getName()."";
            $subcats = $category->getChildren();
            if($subcats != ''){
                $html .= getTreeCategories($category->getId(), true);
            }
            $html .= '</li>';
        }
        $html .= '</ul>';
        return $html;
    }
    $catlistHtml = getTreeCategories($rootCatId, false);

    echo $catlistHtml;

?>

With this code all categories shown. How I can get this tree only from the specific category with ID 7?

Was it helpful?

Solution

Try replacing this line:

$catlistHtml = getTreeCategories($rootCatId, false);

with this one:

$catlistHtml = getTreeCategories(7, false);

OTHER TIPS

If anyone is looking for a function just to dump out the whole category tree:

<?php

require_once '../app/Mage.php';
Mage::app(1);

$rootCatId = Mage::app()->getStore()->getRootCategoryId();

function getTreeCategories($parentId, $isChild){
    $allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')
                ->addAttributeToFilter('include_in_menu','1')
                ->addAttributeToFilter('parent_id',array('eq' => $parentId));

    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    $html .= '<ul class="'.$class.'">';
    //$children = Mage::getModel('catalog/category')->getCategories(7);
    foreach ($allCats as $category) 
    {
        $html .= '<li>'.$category->getName()."";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}
$catlistHtml = getTreeCategories($rootCatId, false);

echo $catlistHtml;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top