I have get the overall category collection by calling this sample code in xml file.

<block class="Magento\Catalog\Block\Product\ListProduct" name="category.products.list" as="product_list" template="Magento_Catalog::product/list.phtml">

This will return the overall category collection but i want to get the specific category collection by category id .I don't want to use object manager or want to create a custom module

1 Answer 1

  namespace Mage\Mohit\Block;
  class Category extends 
    public function __construct(
       array $data = []
        ) {
    $this->categoryRepository = $categoryRepository;
    parent::__construct($context, $data);

    /* $categoryId as category id */
     public function getCategoryById($categoryId){
         try {
  return $category = $this->categoryRepository- 
    } catch 
   (\Magento\Framework\Exception\NoSuchEntityException $e) 
        return ['response' => 'Category Not Found'];

Call From template file, Pass argument as Category id,

$categoryId = 5; // category id $getCategory = $block->getCategoryById($categoryId); echo $getCategory->getName();echo "<br>"; echo $getCategory->getUrlKey();echo "<br>"; echo $getCategory->getIsActive();echo "<br>"; echo "<pre>";print_r($getCategory->getData());

And more refer this link :-


Any query let me know..


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.