Magento 2 – How to Check if on Category Page or Product Page

categorymagento2

Is there a way I can check that If a user on a category page,or an individual product page in Magento 2?

Any help would be greatly appreciated!

Best Answer

You can try below code it might help you.

Inject an instance of \Magento\Framework\App\Request\Http in your class constructor.

If you are in a controller you don't need to do it. You can already access it like this $request = $this->getRequest()

public function __construct(
    ...
    \Magento\Framework\App\Request\Http $request
) {
    ...
    $this->_request = $request;
}

Then you can check if is category or product like this:

if ($this->_request->getFullActionName() == 'catalog_product_view') {
    //you are on the product page
}
if ($this->_request->getFullActionName() == 'catalog_category_view') {
    //you are on the category page
}