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.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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.
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);
$myrootcats = array('12,15,18,20');
foreach($myrootcats as $myrootcat) {
$cat = Mage::getModel('catalog/category')->load($myrootcat);
/*Returns comma separated ids*/
$subcats = $cat->getChildren();
}
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);