I have the following category setup in my magento store:

store root
bedroom    kitchen     bathroom    
|            |            |            
furniture  furniture   furniture         
lighting   lighting    misc

I need to be able to check if the category misc exists as a subcategory in my current category or not, and if so show a particular block.

So if i was in the kitchen category it would not show but in bedroom and bathroom it would.

How can i do this this check?

1 Answer 1


You can get the list of subcategories of a category like this:

$currentCategoryId = 10; 
$collection = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToFilter('is_active', 1) //only active categories
    ->addAttributeToFilter('parent_id', $currentCategoryId);

If you want to check if only a specific category is present...in your case with the name 'misc' just add an additional filter to the code above:

$currentCategoryId = 10; 
$collection = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToFilter('is_active', 1) //only active categories
    ->addAttributeToFilter('parent_id', $currentCategoryId)
    ->addAttributeToFilter('name', 'misc') //filter by name
    ->setPage(1,1) //set a limit to the collection

And you don't even need to load the full collection. You just need to check if the collection from above has at least 1 item in it.

if ($collection->getSize() == 1) {
    // 'misc' exists
    $url = $collection->getFirstItem()->getUrl();
else {
    // no 'misc' subcategory for you.
  • Spot on, thank you. One last thing where you have //'misc' sub category exists and i would be showing my block, how can i get the link of that particular misc category from $collection?
    – odd_duck
    May 26, 2014 at 13:04
  • @odd_duck. I've changed a bit the code and now you can get the subcategory url also.
    – Marius
    May 26, 2014 at 13:12
  • @Marius You can get current category id by using this <?php echo Mage::getModel('catalog/layer')->getCurrentCategory()->getId(); ?> or $this->getLayout()->getBlock('product_list')->getCategoryId(); Then why don't you ..?
    – Elavarasan
    May 26, 2014 at 13:24
  • @Elavarasan. I didn't know the context where the category id was needed. I just put the code as a proof of concept. The source of the category id is not important. You can even get it like this Mage::registry('current_category')->getId().
    – Marius
    May 26, 2014 at 13:32

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.