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 category
3 Answers
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();
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();
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. Aug 23, 2018 at 5:58