1

How can I list subcategories of some category in a static block?

UPDATE: It seems there already is a widget available for this in Github

1
  • Not compatible with the PHP version I have to run 2.3.1
    – Krista K
    Jun 16, 2019 at 8:13

1 Answer 1

1

Mukesh Chapagain has a great tutorial on this. You might need to adapt some things, but this should help.

http://blog.chapagain.com.np/magento-2-get-parent-category-children-categories-product-count/

This is how I did it.

    public function getCategory($categoryId) 
    {
        $this->_category = $this->_categoryFactory->create();
        $this->_category->load($categoryId);        
        return $this->_category;
    }
public function getAllChildren($asArray = false, $categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getAllChildren($asArray);
        } else {
            return $this->getCategory($categoryId)->getAllChildren($asArray);
        }
    }
     public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
    }
        public function getTotalProductCount($categoryId)
        {
            $totalCount = 0;
            $categoriess = $this->getStoreCategories(true, false, true);
            $babies = $this->getAllChildren(true, $categoryId);
            foreach($babies as $babe){
                $babeDetails = $this->getCategory($babe);
                $totalCount = $babeDetails->getProductCount() + $totalCount;
            }

            return $totalCount;
        }

Instead of returning the count you could return the names or whatever would apply to you.

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.