Magento – How to check category has grandchild

categoryce-1.7.0.2navigation

How to check category has grand children exist in any of its children using category id?

Best Answer

SO you have the main category id...

$categoryId = 9;
//get the category object
$category = Mage::getModel('catalog/category')
   ->setStoreId(Mage::app()->getStore()->getId())
   ->load($categoryId);

Remember that all categories have a path setting where all the category tree from root to the category in question is kept. Something like: 1/2/5/27.
Now all you need to do is check if there is a category with the path that starts with the path of your main category and is 2 levels down.

$collection = Mage::getModel('catalog/category')->getCollection()
    ->addPathsFilter($category->getPath().'/') //this will add a filter 'where path like '$path%''
    ->addAttributeToFilter('is_active', 1)//if you want to check if there are enabled grandchildren
    ->addAttributeToFilter('level', $category->getLevel() + 2);// search for categories 2 levels down.

Now all you have to do is see if there are items in your collection.

if ($collection->getSize() > 0) {
    //$category has grand children
}
else{
    //$category does not have grand children
}
Related Topic