This article explains how to retrieve parent categories, subcategories, and the total number of products within a category in Magento 2.

The following code demonstrates a block class for a custom module Mavenbird_HelloWorld. It utilizes \Magento\Catalog\Model\CategoryFactory, \Magento\Catalog\Helper\Category, and \Magento\Catalog\Model\CategoryRepository to manage categories effectively.

Block Class Implementation

The block class is defined in the custom module Mavenbird_HelloWorld. Below is the implementation:

app/code/Mavenbird/HelloWorld/Block/HelloWorld.php
namespace Mavenbird\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_categoryFactory;
    protected $_category;
    protected $_categoryHelper;
    protected $_categoryRepository;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,        
        array $data = []
    ) {
        $this->_categoryFactory = $categoryFactory;        
        $this->_categoryHelper = $categoryHelper;
        $this->_categoryRepository = $categoryRepository;
        parent::__construct($context, $data);
    }
    
    /**
     * Get category object using $_categoryFactory
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCategory($categoryId) 
    {
        $this->_category = $this->_categoryFactory->create();
        $this->_category->load($categoryId);        
        return $this->_category;
    }
 
    /**
     * Get category object using $_categoryRepository
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCategoryById($categoryId) 
    {
        return $this->_categoryRepository->get($categoryId);
    }
 
    /**
     * Retrieve current store categories
     *
     * @return \Magento\Framework\Data\Tree\Node\Collection or array
     */
    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true) 
    {
        return $this->_categoryHelper->getStoreCategories();
    }
    
    /**
     * Get parent category object
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getParentCategory($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentCategory();
        } else {
            return $this->getCategory($categoryId)->getParentCategory();        
        }        
    }
    
    /**
     * Get parent category identifier
     *
     * @return int
     */
    public function getParentId($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentId();
        } else {
            return $this->getCategory($categoryId)->getParentId();
        }
    }
    
    /**
     * Get all parent categories ids
     *
     * @return array
     */
    public function getParentIds($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentIds();
        } else {
            return $this->getCategory($categoryId)->getParentIds();
        }        
    }
    
    /**
     * Get all children categories IDs
     *
     * @param boolean $asArray return result as array instead of comma-separated list of IDs
     * @return array|string
     */
    public function getAllChildren($asArray = false, $categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getAllChildren($asArray);
        } else {
            return $this->getCategory($categoryId)->getAllChildren($asArray);
        }
    }
 
    /**
     * Retrieve children ids comma separated
     *
     * @return string
     */
    public function getChildren($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getChildren();
        } else {
            return $this->getCategory($categoryId)->getChildren();
        }        
    }    
}
    

Key Functionalities

  • Getting Category Objects: Fetching category details using CategoryFactory and CategoryRepository.
  • Retrieving Store Categories: Accessing the list of current store categories with options for sorting and loading them as a collection.
  • Accessing Parent Category Details: Retrieving parent category objects, IDs, and all parent IDs.
  • Fetching Child Categories: Getting all child category IDs as an array or a comma-separated list.
  • Getting Children IDs: Extracting child category IDs in a comma-separated format.

Using Object Manager

The following example demonstrates how to use Magento’s Object Manager to perform similar operations:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();		
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');

$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

$categoryId = 21; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

//var_dump($category->getData());

$parentCategories = $category->getParentCategories();
$childrenCategories = $category->getChildrenCategories();

$storeCategories = $categoryHelper->getStoreCategories();
    

Conclusion

By following this guide, you can efficiently manage and display category structures and product counts in your Magento 2 store. Whether using dependency injection or the Object Manager, these methods ensure flexibility and consistency in category management.