Home » Magento, Magento 24 March 2016

Magento 2: Get parent category, children categories & product count

This article shows how we can get parent category, children categories and total number of products in a category in Magento 2.

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\CategoryFactory class in the constructor of my module’s block class.

Objects of class \Magento\Catalog\Helper\Category and \Magento\Catalog\Model\CategoryRepository as also used in the constructor. They will be used to print a nested list of categories and sub-categories.


Now, we fetch and print the category, parent category, children categories and product count in template file.

Using Object Manager

Hope this helps. Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • Melf.nl

    Great stuff, just a small piece of advice: in the functions where the categoryId is an optional parameter it would make sense to check that first before you use the $_category object. Let’s say I want to get all child category’s for id=10. I call the correct function with the correct attribute, but I might get the child categories from the protected $_category object.

  • Dhananjay Singh

    None of these is working on magento


    on claiing this getting below error


    $childrenCategories = $category->getChildrenCategories();

    Fatal error: Call to a member function getChildrenCategories() on null in

  • Dhananjay Singh

    First question do i need to create a module to use this code, or i can place just this file.

    I can use these functions in any template file or only in template files of module if module creation is necessary.

  • mageDev0688

    How I can display the categories images using your code please help me.