Site icon MageComp Blog

How to display subcategories information on category page in Magento 2

Display Subcategory in Category Page Magento 2

Gone those days when customers need to struggle a lot while finding product or services. The new age of customizations helps the customer to get rid of old typical shopping experience while finding information on a site or store by serving easy navigation layout.

By default inside Magento store, products listed under the hood of the master category even there are tons of subcategories. It makes difficult for the user who wants see products that fall under the particular category. Instead of organizing and showcasing these subcategories under master or root category helps the users to understand easily navigate within products based on their interest. Also, maybe you are probably thinking of implementing such functionality since long while scrolling through some ringmasters like Flipkart and Amazon.

So, without wasting much time, here is your code to display subcategories information on the category page in Magento 2.
Before proceeding you need to keep in mind that category image is required for displaying and make sure that category is enabled.

Now add this below code to your theme ‘list.pthml’ file.
app\design\frontend\Themes\Yourtheme\Magento_catalog\templates\product\list.phtml

<pre class="lang:default decode:true">
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
$subcats = $category->getChildrenCategories();                                                   	
?>
<div class="product details product-item-details">
    <?php
	foreach ($subcats as $subcat) {
    	if ($subcat->getIsActive()) {
                                	$sub_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
                                	$subcat_url = $subcat->getUrl(); ?>
            <span class="product-image">
            <a href="<?php echo $subcat_url; ?>">
                     	<img src="<?php echo $sub_category->getImageUrl() ?>" height="300px" width="240px">
            </a>            	
            </span>
       	   <span class="product-item-name">
             <a href="<?php echo $subcat_url?>" class="product-item-link"><?php echo $subcat->getName(); ?></a>
             </span>
            <?php                        	
    	}
	} ?>
</div>
</pre>

You can use inside this code on any of your Store CMS page as per your need.

Lastly, hit that below stars if the code worked for you and don’t forget to comment down below if you are looking for any help regarding this code.

Happy Coding.

Exit mobile version