Below code is used when flat_category enable from admin with current category get child category.
app/code/Test/Categorytree/view/frontend/templates/listing.phtml
<?php
$currentCategory = $this->getCurrentCategoryInfo();
$noOfCategory = count($currentCategory);
?>
<?php if($noOfCategory) { ?>
<ul class="listing-category-manual">
<?php
foreach($currentCategory as $categoryDetails){
$categoryId = $categoryDetails->getId();
$categoryObj = $this->getCategoryData($categoryId);
$categoryUrl = $categoryObj->getUrl();
$categoryName = $categoryDetails->getName();
?>
<li class="listing-item">
<div class="product details product-item-details">
<a href="<?php echo $categoryUrl; ?>">
<div class="listing-category-info">
<span class="category-name"><?php echo $categoryName; ?></span>
</div>
</a>
</div>
<?php
$getSubCategory = $this->subCategory($categoryObj->getId());
if(count($getSubCategory) > 0){
?>
<ul>
<?php foreach($getSubCategory as $subcat){
$subId = $subcat['entity_id'];
$subcategoryObj = $this->getCategoryData($subId);
$categoryUrl = $subcategoryObj->getUrl();
$categoryName = $subcategoryObj->getName();
?>
<li>
<a href="<?php echo $categoryUrl; ?>">
<div class="listing-category-info">
<span class="category-name"><?php echo $categoryName; ?></span>
</div>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } //endforeach ?>
</ul>
<?php } ?>
app/code/Test/Categorytree/Block/Subcategory.php
<?php
namespace Test\Categorytree\Block;
use Magento\Framework\App\Filesystem\DirectoryList;
class Subcategory extends \Magento\Framework\View\Element\Template
{
protected $categoryFactory;
protected $layerResolver;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
array $data = []
) {
$this->categoryFactory = $categoryFactory;
$this->_catalogLayer = $layerResolver->get();
parent::__construct(
$context,
$data
);
}
public function getCurrentCategoryInfo(){
$categories = $this->_catalogLayer->getCurrentCategory()->getChildrenCategories();
return $categories;
}
public function getCategoryData($id){
return $category = $this->categoryFactory->create()->load($id);
}
public function subCategory($id){
$category = $this->getCategoryData($id);
$childs = $category->getChildrenCategories();
foreach($childs as $child){
$subchild[] = $child->getData();
}
return $subchild;
}
}
Define inside static block below code,
{{block class="Test\Categorytree\Block\Subcategory" template="Test_Categorytree::listing.phtml"}}</p>
call static block in your category from backend.
Go to Category
Content Tab,
Content -> Add CMS Block set your cms block.
Display settings Tab:
select Display mode value as static block only from dropdown.