How to Get all the Child Categories IDs of the Specific Category in Magento 2?

 Steps to Get all the Child Categories IDs of the Specific Category in Magento 2:

Say, you have the following categories in your Magento 2 store.


categories


To get category IDs, follow the below step.


Step 1: Create a file in your Magento root directory at the below path


magento_root_directory\getcategory.php


Then add the code as follows.


<?php

 

use Magento\Framework\AppInterface;

ini_set('display_errors', TRUE);

try

{

    require_once __DIR__ . '/app/bootstrap.php';

}

catch (\Exception $e)

{

    echo 'Autoload error: ' . $e->getMessage();

    exit(1);

}

 

try

{

    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

    $appState = $objectManager->get('\Magento\Framework\App\State');

    $appState->setAreaCode('frontend');

    

    $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');// Instance of Category Model

    $rootCategoryId = 2; // your root category Id

    $category = $categoryFactory->create()->load($rootCategoryId);

    $categoryIds= $category->getAllChildren(false);

    echo $categoryIds; //will return comma separated list of ids

}

catch (Exception $e)

{

    echo $e->getMessage();

}

 

?>

Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Update Product Stock Programmatically in Magento 2

How to Set and Get Cookie in Magento 2