Magento 2: How to Get Subcategories of Specific Parent Category



<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$catId = 2; // Parent Category ID
$subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
$subcats = $subcategory->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 */

} ?>
< li>
< div class="cat-image">
< a href="<?php echo $subcaturl ?>"><?php echo $_imgHtml;?></a>
< /div>
< div class="info">
< h4><?php echo $subcat->getName(); ?></h4>
< a class="link" href="<?php echo $subcaturl ?>"><?php /* @escapeNotVerified */ echo __('View more') ?></a></div>
< /li>
< ?php } ?>
< /ul>

Advertisements