How to get Current Category details in magento 2?

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.

How to get Category collection by Category id in magento 2?

You can get category collection by category id by below code snippet,

<?php
namespace Rbj\Category\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());

 

 

How to get Category Collection per Storewise in Magento 2?

When we have multi-store setup and store have different category assigned at that time we need to get store wise category collection.
We can get store wise category collection by below code snippet.

1. Use directly Objectmanager is not best/Recommended way to do in Magento, use Block with the construct() and fetch method in your phtml file.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Helper\Category');
$categoryFactory->getStoreCategories(false,false,true);

2. Recommended Way Using Create Block file and call from the template,

Create Block PHP file,

<?php
namespace Rbj\Training\Block\Index;

class Training extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Category $categoryHelper,
        array $data = []
    ) {
        $this->_categoryHelper = $categoryHelper;
        parent::__construct($context, $data);
    }

     /**
     * Retrieve current store level 2 category
     *
     * $sorted (if true display collection sorted as name otherwise sorted as based on id asc)
     * $asCollection (if true display all category otherwise display second level category menu visible category for current store)
     * $toLoad
     */
    public function getMainStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }

    /* Here we have passed sorted as true so category display as Name ASC order */
    public function getAllCurrentStoreCategories($sorted = true, $asCollection = true, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }
}

Display second level category, all those categories which have Level equals 2. call below function from a template file,

$getLevel2Category = $block->getMainStoreCategories();
foreach($getLevel2Category as $category) {
    echo $category->getName();echo "<br>";
}

For getting all categories of current store call below function in template file,

$getCategory = $block->getAllCurrentStoreCategories();
foreach($getCategory as $category) {
    echo $category->getName();echo "<br>";
}

You can change the custom argument by passing argument on above function from template file.