Magento – Magento 2: How to Get Subcategory Image in Category Page

catalogcategory-viewimagemagento-2.0

I want to display subcategory in category page with the image.
I've to put below code get only subcategory name not getting the image.

How to get subcategory image in category page?

if($this->getLayer()->getCurrentCategory())

            $subcategories=$this->getLayer()->getCurrentCategory()->getCategories($this->getLayer()->getCurrentCategory()->getId());


            if($subcategories->count()>0){

                foreach($subcategories as $subcategory){

                   <li>
                      <a href="<?php echo $subcategory->getRequest_path(); ?>"><?php echo $subcategory->getName() ?></a>
                   </li> 
                }      
            }else{}

endif;

Best Answer

i used this block to have the same functionality and called the block in xml ( don't forget to create a template for the block with the desired functionality and html mockup

namespace Namespace\Module_Name\Block;

class Subcategories extends \Magento\Framework\View\Element\Template
{

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_registry;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    protected $_categoryCollectionFactory;

    /**
     * @var \Magento\Catalog\Helper\Category
     */
    protected $_categoryHelper;

    /**
     * Subcategories constructor.
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {
        $this->_registry = $registry;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryHelper = $categoryHelper;
        parent::__construct($context, $data);
    }


    public function getCurrentCategory()
    {
        return $this->_registry->registry('current_category');
    }


    public function getCategoryCollection(){
        $_category = $this->getCurrentCategory();
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*')
            ->addAttributeToFilter('is_active', 1)
            ->setOrder('position', 'ASC')
            ->addIdFilter($_category->getChildren());

        return $collection;
    }


}
Related Topic