Magento 2 – Display Sub Category of Parent

magento2

Magento 2 Display Sub Category of parent? I am trying to get subcategory using current category registry object but i don't know how to getChildrenCategories for parent.

Best Answer

My code to get the category list for the main category is:

public function __construct(
        Template\Context $context, 
        \Magento\Catalog\Model\Layer\Resolver $layerResolver, 
        \Magento\Framework\Registry $registry, 
        \Magento\Catalog\Helper\Category $categoryHelper, 
        \Magento\Catalog\Model\CategoryFactory  $categoryFactory,
        array $data = array()) 
    {
        parent::__construct($context, $layerResolver, $registry, $categoryHelper,$data);
        $this->_categoryFactory = $categoryFactory;
        $this->_collectionFactory = $collectionFactory;
     }

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

    }
Related Topic