Hello magento friends todays in this blog post im share with you to How to Get all the Child Categories IDs of the Specific Category in Magento 2.
In Magento 2, you can get all the child category IDs of a specific category using the CategoryFactory and CategoryRepository. Here's a step-by-step guide on how to achieve this programmatically:
- First, make sure you have the necessary setup to create a custom module. If you already have a custom module, you can skip this step.
- Create a custom module (if you haven't already) and navigate to the module's directory.
- Create a new PHP file, for example, "ChildCategories.php," inside the module's Block folder.
- In the "ChildCategories.php" file, add the following code:
<?phpnamespace [Vendor]\[Module]\Block;use Magento\Catalog\Api\CategoryRepositoryInterface;use Magento\Catalog\Model\CategoryFactory;use Magento\Framework\View\Element\Template;use Magento\Framework\View\Element\Template\Context;class ChildCategories extends Template{protected $categoryRepository;protected $categoryFactory;public function __construct(Context $context,CategoryRepositoryInterface $categoryRepository,CategoryFactory $categoryFactory,array $data = []) {parent::__construct($context, $data);$this->categoryRepository = $categoryRepository;$this->categoryFactory = $categoryFactory;}public function getChildCategoryIds($categoryId){$childIds = [];$category = $this->categoryRepository->get($categoryId);if ($category->hasChildren()) {$children = $category->getChildrenCategories();foreach ($children as $child) {$childIds[] = $child->getId();}}return $childIds;}}
- Replace [Vendor] and [Module] with your custom module's vendor and module names, respectively.
- Save the file and go to your Magento 2 root directory in the terminal.
- Run the following commands to enable the module and clear the cache:
php bin/magento module:enable [Vendor]_[Module]php bin/magento setup:upgradephp bin/magento cache:clean
Now, you can use the "getChildCategoryIds" method in your template file or other classes. For example, if you want to display the child category IDs of a specific category in your template file, create a new .phtml file and use the following code:
<?php$categoryId = 10; // Replace with the ID of the category you want to get the child categories for$childCategoriesBlock = $block->getLayout()->createBlock('[Vendor]\[Module]\Block\ChildCategories');$childCategoryIds = $childCategoriesBlock->getChildCategoryIds($categoryId);// Now, you can use $childCategoryIds as an array containing the child category IDs
Replace "10" with the actual ID of the category you want to get the child categories for.
That's it! Now you should be able to retrieve all the child category IDs of a specific category in Magento 2 using this custom block.
Tags:
magento2