0

I'm new to magento, i like to create own module for getting child category name and image in category page. Created Vendor name as "Sub" and modulename as "Categories"

app/code/Sub/Categories/View/frontend/templates/sub.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>

app/code/Sub/Categories/Block/sub.php

<?php
namespace Sub\Categories\Block;

class Sub 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;
    }
}

finally i create new block

{{block class="Sub\Categories\Block\sub" template="Sub_Categories::sub.phtml"}}

and assigned in widget.

Please let me know is any thing wrong in it. It does not change any thing in front-end.

7
  • where you used that widget? Commented Apr 23, 2019 at 11:31
  • Hi, @DhirenVasoya . In admin-> content-> widgets i create new widgets and in Widget Options-> "i selected custom block" that i add "{{block class="Sub\Categories\Block\sub" template="Sub_Categories::sub.phtml"}}"
    – Priya
    Commented Apr 23, 2019 at 11:39
  • first debug your code that, does your phtml file call? Does you get current category from the registry? Commented Apr 23, 2019 at 11:40
  • Now i get current sub-category product image and their details list. above that i like to display only sub-category name and sub category image.
    – Priya
    Commented Apr 23, 2019 at 11:45
  • What I told that debug, does your phtml file called? I think this file is not call, so first confrim that. Commented Apr 23, 2019 at 11:52

2 Answers 2

1

Firstly, if you need this in custom phtml file then you need to include \Magento\Catalog\Block\Category\View block class file.

Or if you are overriding any category phtml template in your design then you can use below code:


<?php

$helper = $this->helper(Magento\Catalog\Helper\Category::class);
?>
<?php if ($_description = $block->getCurrentCategory()->getDescription()) :?>
    <div class="category-description">
        <?= $block->getCmsBlockHtml() ?>

        <?php 
            $categorys = $helper->getStoreCategories(false,false,true); 
            foreach($categorys as $category)
            {
                $subCategoriesOptions = [];
                $subCategories = (array) $category->getChildrenNodes();

                if ($subCategories)
                {
                    foreach ($subCategories as $value)
                    {
                        $subCategoriesOptions[$value->getId()] = $value->getName();
                    }
                }

            }
            //print_r($subCategoriesOptions);
            //exit;
        ?>
0

You need to do following things.

  1. Overide Category List file into your extension.

app\code\Sub\Categories\view\frontend\layout\catalog_category_view.xml

<?xml version="1.0"?>
<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="category.products.list">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Sub_Categories::sub.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>
  1. Run the caching and commands and then check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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