Search This Blog

Sep 12, 2012

How to display subcategories anywhere in Magento

If you’re planning to display the subcategories of a specific root/parent category anywhere you can simply use the following code and paste it in your the phtml files that you want it to show. Just please take note that you need to replace the id in the code.

<?php
$root = Mage::getModel('catalog/category')->load(2); // Put your category ID here.

//get the children of your loaded category and exploded in array
$subCat = explode(',',$root->getChildren()); 

//get the collection add filter using the exploded categories
$collection  = $root->getCollection()->addAttributeToSelect("*")->addFieldToFilter("entity_id", array("in", $subCat) );

//loop for each subscategory in a collection
foreach($collection as $subcategory) { 
 echo '<a href="'.$subcategory->getURL() .'" />'.$subcategory->getName().'</a><br/>';
}
 
?>

You can get the ID in your admin panel by going to Catalog>Manage Categories. Click the category that you want in the category tree. Then look for the ID beside the category name.


You can post the above code in any phtml files of your theme.

0 comments: