I need to display all the sub categories under every category as a grid in relevant pages with linked images. Is there a way to do it ? I am using magento 2.2.4

  • What about the products of that category? – Sukumar Gorai Jul 17 '18 at 12:46
  • @SukumarGorai When clicking on the sub category image, I need to redirect it to the relevant products page – SMash Jul 18 '18 at 3:33
  • So you mean if any of the category have subcategories then need to show subcategories page and if no subcategories then redirect to relevant listing page. Right? – Sukumar Gorai Jul 18 '18 at 5:46
  • @SukumarGorai Yes that is how it needs – SMash Jul 18 '18 at 6:07

You need to copy the below file:


to your theme like below:


And add the below code to product.phtml:

<?php $category = $block->getCurrentCategory(); ?>
<?php $subcategories = $category->getChildrenCategories(); ?>
<?php $_helper = $this->helper('Magento\Catalog\Helper\Output'); ?>
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); ?>
<?php if(count($subcategories) > 0): ?>
    <div class="products wrapper grid products-grid">
        <ol class="products list items product-items">
            <?php foreach($category->getChildrenCategories() as $subcategory): ?>
                <?php $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($subcategory->getId()); ?>
                <li class="item product product-item">
                    <div class="product-item-info">
                        <?php if ($_imgUrl = $subcategory->getImageUrl()): ?>
                            <a href="<?= $subcategory->getUrl() ?>" class="product photo product-item-photo">
                                <span class="product-image-container">
                                    <?php $_imgHtml = '<img src="' . $_imgUrl . '" />'; ?>
                                    <?php echo $_imgHtml = $_helper->categoryAttribute($subcategory, $_imgHtml, 'image'); ?>
                        <?php endif; ?>
                        <div class="product details product-item-details">
                            <strong class="product name product-item-name">
                                <a class="product-item-link" href="<?= $subcategory->getUrl() ?>"><?= $subcategory->getName() ?></a>
            <?php endforeach; ?>
<?php else: ?>
    <?php if (!$block->isContentMode() || $block->isMixedMode()): ?>
        <?= $block->getProductListHtml() ?>
    <?php endif; ?>
<?php endif; ?>

You need to manage the css according to your requirement and also need to hide the layered navigation through css or update it to 1 column according to your requirement.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.