cancel
Showing results for 
Search instead for 
Did you mean: 

Display Subcategories on Category Page

Display Subcategories on Category Page

Hello All,

 

I'm a fresher in learning Magento (Ver 2.4), so didn't know every nooks & corner of it. I know this question has been asked many times. I googled and found few solutions and tried to implement one but unsuccessful. The category page is not listing its sub-categories. Below is my attempt to implement the needful:

 

Block file (Display.php)

<?php
namespace Javansar\Category\Block;

class Display extends \Magento\Framework\View\Element\Template
{
    protected $_categoryHelper;
    protected $categoryFlatConfig;
    protected $topMenu;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
        \Magento\Theme\Block\Html\Topmenu $topMenu
    )
    {
        $this->_categoryHelper = $categoryHelper;
        $this->categoryFlatConfig = $categoryFlatState;
        $this->topMenu = $topMenu;
        parent::__construct($context);
    }

    /**
     * Return categories helper
     */
    public function getCategoryHelper()
    {
        return $this->_categoryHelper;
    }

    /**
     * Return categories helper
     * getHtml($outermostClass = '', $childrenWrapClass = '', $limit = 0)
     * example getHtml('level-top', 'submenu', 0)
     */
    public function getHtml()
    {
        return $this->topMenu->getHtml();
    }

    /**
     * Retrieve current store categories
     *
     * @param bool|string $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return \Magento\Framework\Data\Tree\Node\Collection|\Magento\Catalog\Model\Resource\Category\Collection|array
     */
    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
    }

    /**
     * Retrieve child store categories
     *
     */
    public function getChildCategories($category)
    {
        if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
            $subcategories = (array)$category->getChildrenNodes();
        } else {
            $subcategories = $category->getChildren();
        }
        return $subcategories;
    }
}

Template (categories.phtml)

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
$subcats = $category->getChildrenCategories();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<ul>
    <?php
    foreach ($subcats as $subcat) {
        if ($subcat->getIsActive()) {
            $_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 */
                echo '<li><a href="' . $subcaturl . '" class="block-promo" title="' . $subcat->getName() . '">' . $_imgHtml . '<span style="background-color: rgba(255,255,255,0.9)" class="content bg-white"><strong>Place custom code here</strong><br><br><span class="action more button">Learn More</span></span></a></li>';
            }
        }
    } ?>
</ul>

Layout (catalog_category_view.xml)

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <body>
        <referenceBlock name="electronics-new">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">%Javansar_Category::categories.phtml%</argument>
            </action>
        </referenceBlock>
    </body>
</page>

 

Setting in CMS:

 

Electronics category

Category settingsCategory settings

Block Setting:

Block settingsBlock settings

 

 

Widget Setting:Widget Setting 1Widget Setting 1Widget Setting 2Widget Setting 2

Electronic page: This is the output i'm getting

page.JPG

I think the issue is somewhere between the xml and phtml file but I'm not able to find it. Can anyone please help me in achieving this?

 

 

Much Regards,

Javed Ansari

3 REPLIES 3

Re: Display Subcategories on Category Page

You may find this helpful

https://meetanshi.com/blog/display-magento-2-subcategories-with-image-on-category-page/

for the required solution.

Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.

Re: Display Subcategories on Category Page

Thanks Sanjay for your guidance. However, i would like follow the block & templating system as currently I'm trying on.

 

However, I've made few changes in my attempt (thanks to your another guidance of templates hinting). Can you please go through my reply below and suggest me some workaround?

Re: Display Subcategories on Category Page

Hello All,

I have made below changes still its not working:

 

1) Removed the layout folder and its catalog_category_view.xml file

2) Enable Template Path Hints

 

Current view of the category page:

report.JPG

 

Block file (Display.php)

 

<?php
namespace Javansar\Category\Block;

class Display extends \Magento\Framework\View\Element\Template
{
    protected $_categoryHelper;
    protected $categoryFlatConfig;
    protected $topMenu;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
        \Magento\Theme\Block\Html\Topmenu $topMenu
    )
    {
        $this->_categoryHelper = $categoryHelper;
        $this->categoryFlatConfig = $categoryFlatState;
        $this->topMenu = $topMenu;
        parent::__construct($context);
        echo 'hi there';
    }    

    public function getMsg()
    {
        return "<br>Hello from func";
    }
}

 

Template file (categories.phtml)

 

<h1><?php echo $block->getMsg(); ?></h1>

 

Block section in Adminpanel

block.JPG

 

You can see that the message from the constructor in the Block file is being displayed. However, its method is not being called from the template file.

 

I believe its the template file which is not being rendered. I have cleared the cache many times still no success

 

Below is the folder & file structure in my system

structure.JPG