0

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

  • the question is bit unclear, please explain it in detail.. – Dexter Jun 27 '14 at 16:59
4

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
}
  • If path is 1/2/5/2 its returns grandchildren of as well 1/2/5/27 – Sandesh Jul 1 '14 at 11:21
  • 1
    Need to update as ->addPathsFilter($category->getPath()) as ->addPathsFilter($category->getPath().'/') – Sandesh Jul 1 '14 at 11:27
  • @ganesh Damn. You are right. I updated the answer. – Marius Jul 1 '14 at 11:27
0
echo hasGrandchild(13); // parent Category id

function hasGrandchild($id){
   $categories = Mage::getModel('catalog/category')->load($id)->getChildren();
   $catArray = explode(',', $categories);
   $hasChild=false;
   foreach($catArray as $child){
         $_child = Mage::getModel( 'catalog/category' )->load( $child );
     if($_child->getChildrenCount()){
        $hasChild=true;
    }
    }
return $hasChild;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.