Current Category collection can be found if you are in category page otherwise you can’t get current category collection using Registry. Refer below code snippet for getting current category collection in Magento 2,
<?php namespace Rbj\Category\Block; class CurrentCategory extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Registry $registry, array $data = [] ) { $this->registry = $registry; parent::__construct($context, $data); } /* $categoryId as category id */ public function getCategory(){ try { return $this->registry->registry('current_category'); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { return ['response' => 'Category Not Found']; } } }
Call From template file,
<?php $getCategory = $block->getCategory(); if($getCategory) { echo $getCategory->getName();echo "<br>"; echo $getCategory->getUrlKey();echo "<br>"; echo $getCategory->getIsActive();echo "<br>"; echo "<pre>";print_r($getCategory->getData()); } else { echo 'Current page is not a category page'; }
If you are in category page, you got Current category details by above code snippet otherwise display the message like, Current page is not a category page
You can check Get Sub Category details by parent id Magento.