In many places we will need to get the category tree in magento programmatically. With the below peace of code you can get the tree anywhere in magento
$rootCatId = Mage::app()->getStore()->getRootCategoryId(); // it will fetch your current store root id
$catlistHtml = getTreeCategories($rootCatId, false);
echo $catlistHtml;
function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1') // is acategory active
->addAttributeToFilter('include_in_menu','1') // to check include_in_menu yes or no
->addAttributeToFilter('parent_id',array('eq' => $parentId)) // filter parent id
->addAttributeToSort('position', 'asc');
$class = ($isChild) ? "sub-cat-list" : "cat-list";
$html .= '<ul class="'.$class.'">';
foreach($allCats as $category)
{
$html .= '<li><span>'.$category->getName()."</span>";
$subcats = $category->getChildren();
if($subcats != ''){
$html .= getTreeCategories($category->getId(), true);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
Please let me know if there is other such easy way to do this.I will love to hear and update my post.
thanks
$rootCatId = Mage::app()->getStore()->getRootCategoryId(); // it will fetch your current store root id
$catlistHtml = getTreeCategories($rootCatId, false);
echo $catlistHtml;
function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1') // is acategory active
->addAttributeToFilter('include_in_menu','1') // to check include_in_menu yes or no
->addAttributeToFilter('parent_id',array('eq' => $parentId)) // filter parent id
->addAttributeToSort('position', 'asc');
$class = ($isChild) ? "sub-cat-list" : "cat-list";
$html .= '<ul class="'.$class.'">';
foreach($allCats as $category)
{
$html .= '<li><span>'.$category->getName()."</span>";
$subcats = $category->getChildren();
if($subcats != ''){
$html .= getTreeCategories($category->getId(), true);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
Please let me know if there is other such easy way to do this.I will love to hear and update my post.
thanks
No comments:
Post a Comment