0

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

0
  <?php
  namespace Mage\Mohit\Block;
  class Category extends 
 \Magento\Framework\View\Element\Template
  {
    public function __construct(
      \Magento\Framework\View\Element\Template\Context 
      $context,
    \Magento\Catalog\Api\CategoryRepositoryInterface 
     $categoryRepository,
       array $data = []
        ) {
    $this->categoryRepository = $categoryRepository;
    parent::__construct($context, $data);
     }

    /* $categoryId as category id */
     public function getCategoryById($categoryId){
         try {
  return $category = $this->categoryRepository- 
    >get($categoryId);
    } 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 :-

https://www.rakeshjesadiya.com/how-to-get-category-collection-by-category-id-in-magento-2/

Any query let me know..

Thanks.

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.