Magento2 Category ID – How to Get Sub Category ID by Current Category ID in Magento2

categoryfrontendmagento2

I want to get sub category id when I click on main category id. For ex. I Click on "Gear" category…Then It will also display sub category's id..

This is block file function :

public function getCurrentCategory(){        
$currentId  = $this->_registry->registry('current_category'); 
return $currentId; // it will return current category id}

This is phtml file :

    <?php 
$currentCategory = $block->getCurrentCategory();//I want to here subcategory id?>

enter image description here

Best Answer

To get child-category of sub-category Try below code :

public function __construct(
    ...
    \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ...
) {
    ...
    $this->categoryRepository = $categoryRepository;
    ...
}

public function getSubcategories()
{   
    $currentId  = $this->_registry->registry('current_category'); 
    $categoryObj = $this->categoryRepository->get($currentId->getId());
    $subcategories = $categoryObj->getChildrenCategories();

    //Print suncategory Ids
    foreach($subcategories as $subcategorie) {
        //echo $subcategorie->getId();
        if($subcategorie->hasChildren()) {
        $childCategoryObj = $this->categoryRepository->get($subcategorie->getId());
        $childSubcategories = $childCategoryObj->getChildrenCategories();
        foreach($childSubcategories as $childSubcategorie) {
            echo $childSubcategorie->getId();
        }
     }    
   }

    return $subcategories;
}

As its category collection so ,You can also use $categoryObj->getPathId() This function return all subcategory Ids of category.

Related Topic