Magento2 Category Grid – Show Subcategory with Images

catalogcategorycategory-productsmagento2magento2.2.4

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

Best Answer

You need to copy the below file:

vendor/magento/module-catalog/view/frontend/templates/category/products.phtml

to your theme like below:

app/design/frontend/[Vendor]/[theme]/Magento_Catalog/templates/category/products.phtml

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'); ?>
                                </span>
                            </a>
                        <?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>
                            </strong>
                        </div>
                    </div>
                </li>
            <?php endforeach; ?>
        </ol>
    </div>
<?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.

Related Topic