Get sub category of current category in magento2
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
Get subcategory of current category
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
$subcats = $category->getChildrenCategories();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<ul class="sub-cat">
<?php
foreach ($subcats as $subcat) {
$_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
$_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
$subcaturl = $subcat->getUrl();
$_imgHtml = '';
if ($_imgUrl = $_category->getImageUrl()) {
$_imgHtml = '<img src="' . $_imgUrl . '" />';
$_imgHtml = $_outputhelper->categoryAttribute($_category, $_imgHtml, 'image');
/* @escapeNotVerified */
echo '<li><a href="' . $subcaturl . '" title="' . $subcat->getName() . '">' . $_imgHtml . '</a></li>';
}
} ?>
</ul>