Magento 2 – Get Subcategory of Current Category

categorymagento2

I want to create custom list (category) page in magento2.

If current category has sub category then it's show sub category.

If current category have sub category and products then it's show both.

If current category has only products then it's show products only.

which file I need to do changes?

Can anyone give me a suggestion?

Best Answer

You can get sub-category by below code at list.phtml

if($this->getLayer()->getCurrentCategory()):
$subcategories=$this->getLayer()->getCurrentCategory()->getCategories($this->getLayer()->getCurrentCategory()->getId());
    /* count and check the category have any sub category */
    if($subcategories->count()>0){

        foreach($subcategories as $subcategory){
            //echo "<pre>";
            //print_r($subcategory->getData());
            echo $subcategory->getName();
        }

    }else{
        // category does not have any sub category
    }
else:
        // category does not have any sub category

endif;

Edit:

add this code:

<!-- add by amit bera -->
    <?php if($this->getLayer()->getCurrentCategory()):   ?>
        <?php 
        if($subcategories->count()>0){

            foreach($subcategories as $subcategory){
                //echo "<pre>";
                //print_r($subcategory->getData());
                echo $subcategory->getName();
            }

        }   
        ?>
    <?php endif ?>

just after <?php if (!$_productCollection->count()): ?>

and

add below code:

<!-- add by amit bera -->
    <?php if($this->getLayer()->getCurrentCategory()):   ?>
        <?php 
        if($subcategories->count()>0){

            foreach($subcategories as $subcategory){
                //echo "<pre>";
                //print_r($subcategory->getData());
                echo $subcategory->getName();
            }

        }   
        ?>
    <?php endif ?>

just after <?php $pos = $block->getPositioned(); ?>

Get source code at http://codepad.org/VwvnFZge

Related Topic