0

I am a beginner. Could you please tell me how to get the current category ID on the magento2 category page? I want to show a specific banner in a specified categoryenter image description here

1

You can get current categoryId in your Block code like below:

  public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Framework\Registry $registry,
    array $data = []
)
 public function getCurrentCategory()
{        
    return $this->_registry->registry('current_category');
}

And you can use it in block like

$category=$block->getCurrentCategory(); and $categoryId=$category->getId();

0

You can use the default Magento block too.

Use Magento\Catalog\Block\Category\View in your layout file as given below.

<block class="Magento\Catalog\Block\Category\View" name="home.slider" template="Vendor_Module::homeslider.phtml" />

Now you can get the current category in your homeslider.phtml as shown below.

$current_category = $block->getCurrentCategory();
0

Please Try below code to get category ID

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get(\Magento\Framework\Registry::class)->registry('current_category');//get current category
    echo $category->getId();
    echo $category->getName();
?>

I hope it will help you

  • This code is fine for a test but should not be deployed in production. – Shawn Abramson Aug 23 '18 at 5:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.