1

For Magento1, On:-

app/design/frontend/Mypackage/Mytheme/template/catalog/product/view.phtml

I'm using following code:-

Mage::getModel('catalog/layer')->getCurrentCategory()->getId()

Same code I want to use for Magento2, how can I achieve?

Note:- Don't want to use registry.

Thanks!!!

1
private $layerResolver;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\Layer\Resolver $layerResolver,
    array $data = []
) {
    parent::__construct($context, $data);

    $this->layerResolver = $layerResolver;
}

public function getCurrentCategoryId()
{
    return $this->layerResolver->get()->getCurrentCategory()->getId();
}

or you can use

$objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
$category_id =  $objectmanager->get('Magento\Catalog\Model\Layer')->getCurrentCategory()->getId();
  • thanks for the reply! by including classes it works & I achive the expected output but objectmanager way doesn't work. – wakar Ahamad Sep 12 '18 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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