0

I am working on a script, my requirement is to get child categories of multiple root categories. Root category is an array of ID's.

Example: $myrootcats = array('12,15,18,20');

And I want all active categories which belong to the above array.

  • 1
    I don't know why you asked the same question twice but I vote to close the old one because the new one is in better form – Fabian Schmengler Oct 7 '15 at 7:09
  • You have not tagged this as magento 1 or magento 2... – stephen Jan 18 '17 at 11:21
1

You can use below code to get all subcategories.

<?php
$myrootcats = array('12,15,18,20');
$catArray = array();
foreach ($myrootcats as $_rootCat)
{
    $children = Mage::getModel('catalog/category')->getCategories($_rootCat);
    foreach ($children as $category)
    {
      if($category->getIsActive()){
        $catArray[] = $category->getId();
      } 
    }
    $catArray[] = $_rootCat;
}
array_unique($catArray);
| improve this answer | |
  • It is also give me inactive subcategory. – Mathew Oct 6 '15 at 11:09
  • edited my answer. Added condition for check is active. – Akhilesh Patel Oct 6 '15 at 11:16
  • Yes working correct.... – Mathew Oct 6 '15 at 11:19
0
$myrootcats = array('12,15,18,20');
foreach($myrootcats as $myrootcat) {
    $cat = Mage::getModel('catalog/category')->load($myrootcat);

    /*Returns comma separated ids*/
    $subcats = $cat->getChildren();
}
| improve this answer | |
0

As you want to filter category by root category id then you can use path category attribute path becuase magento save save root category in path.

require_once "YOurMagentoDirapp/Mage.php";
umask(0);
ini_set('display_errors', 1);
Mage::app("admin");


$buildArray=array();

$rootId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
$rootids= array(12,15,18,20);

foreach($rootid as $id){

  $buildArray[]= array('attribute' =>'path','like'=>$rootId.'/'.$id.'/%');

}

$collection = Mage::getModel('catalog/category')->getCollection()
        ->addFieldToFilter('is_active',1)
->addFieldToFilter($buildArray);

If want to immediate child category of root categories then just change logic of $buildArray

foreach($rootid as $id){

 // $buildArray[]= array('attribute' =>'path','like'=>$rootId.'/'.$id.'/%');
   $buildArray[]= array('attribute' =>'parent_id','eq'=>$id);

}

$collection = Mage::getModel('catalog/category')->getCollection()
        ->addFieldToFilter('is_active',1)

        ->addFieldToFilter($buildArray);
            ->addFieldToFilter($buildArray);
| improve this answer | |
  • there are some mistake..now you see update – Amit Bera Oct 7 '15 at 7:06

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