0

I need to get all category children of a specific category but disabled categories too.

I have this category tree:

+ Root (ID: 2) // enabled
| + Main 1 (ID: 3) // enabled
| | + Sub 1 (ID: 4) // enabled
| + Main 2 (ID: 5) // enabled
| | + Sub 2 (ID: 6) // enabled
| + Main 3 (ID: 7) // disabled

I need to get all childrens of category with ID 2 [Main1(3),Main2(5),Main3(7)].

I tried with:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$parentCategoryId = 2;
$parentCategory = $objectManager->get('Magento\Catalog\Model\Category')->load($parentCategoryId);

/*
Also tried with:
$parentCategory = $objectManager->get('Magento\Catalog\Model\Category')->getCollection()
    ->addIdFilter($parentCategoryId)
    ->addAttributeToFilter('is_active', false/0/null/2) // always return an empty array...
    ->getFirstItem();
*/

$parentCategory->getChildren(); // return [3,5]

$cats = [];
foreach($parentCategory->getChildrenCategories() as $cat)
    $cats[] = $cat->getId();

print_r($cats); // return [3,5]

1 Answer 1

2

Please try below collection.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$parentCategoryId = 2;
$parentCategory = $objectManager->get('Magento\Catalog\Model\Category')->load($parentCategoryId);


    $collection =$objectManager->create("\Magento\Catalog\Model\CategoryFactory")->create()->getCollection()->addAttributeToSelect('*')
                      ->setOrder('position', 'ASC')
              ->addFieldToFilter('is_active',array("in"=>array('0', '1')))
                     ->addAttributeToFilter('parent_id',['eq'=>$parentCategoryId]);

        print_r($collection->getData());

I Hope It's Will Helpful.

enter image description here

10
  • Unfortunately always return 3 and 5, not 7. :(
    – fmineo
    Sep 27, 2019 at 10:38
  • Please try after clean cache and reindex Sep 27, 2019 at 10:44
  • Yes, I did... No changes...
    – fmineo
    Sep 27, 2019 at 10:46
  • Now, can you try with update code, I have working it. Sep 27, 2019 at 11:04
  • $parentCategoryId is 2, but nothing... no changes
    – fmineo
    Sep 27, 2019 at 11:08

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.