Magento 2 : How to check if we are on a category page or product page?
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
}
You can use 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 homepage or categorypage or productpage like this:
if ($this->_request->getFullActionName() == 'cms_index_index') {
//you are on the homepage
}
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
}
Otherwise directly use in phtml file using object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('\Magento\Framework\App\Request\Http');
I guess, we can directly use
$this->getRequest()->getFullActionName()
in .phtml file to get current page action.