Magento How to get category and child/sub categories by category ID

This is one of the easy way to get category and child or sub categories using category id.
You can use following code anywhere in Magento module files.


<?php
$parentCategoryId = 4; // Note: Change you category id here
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1')
->addAttributeToFilter('include_in_menu','1')
->addAttributeToFilter('parent_id',array('eq' => $parentCategoryId))
->addAttributeToSort('position', 'asc');

foreach($allCats as $_category) {
try {
$_subcategories = $category->getChildrenCategories();
if (count($_subcategories) > 0){
echo 'Parent Category Name: '.$_category->getName();
echo 'Parent Category Id: '.$_category->getId();      
foreach($_subcategories as $_subcategory){
echo 'Child Category Name: '. $_subcategory->getName();
echo 'Child Category Id: '.$_subcategory->getId();
}
}
} catch (Exception $ex) {// log your exception here}
}
?>
Magento How to get category and child/sub categories by category ID Magento How to get category and child/sub categories by category ID Reviewed by Web Technology Funda on 11:42:00 PM Rating: 5

No comments

Free! Free!Free! Subscribe to Get Free PHP (Magento) tutorial Update in Your Inbox!!! Hurry Up!!!