3

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?

2 Answers 2

2

Try replacing this line:

$catlistHtml = getTreeCategories($rootCatId, false);

with this one:

$catlistHtml = getTreeCategories(7, false);
7

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;
?>

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.