Magento: How to tell if you're on a category page, or product page in .phtml file(s)

Viewed 44517

I am trying to program into my .phtml files an if statement if the guest is on a category list page, or on a product page.

For example this code:

<?= Mage::app()->getFrontController()->getRequest()->getRouteName(); ?>

Returns "catalog" whenever l'm on a page other than a CMS page.

Is there a way l can use a similar method to know if the user is looking at a root category, sub category or an individual product page?

Any help would be greatly appreciated!

4 Answers

While Alan's answer will work, there is a more direct option, and you were actually on the right track with your code snippet... you just need to inspect the controller name rather than the module name:

<?php Mage::app()->getFrontController()->getRequest()->getControllerName(); ?>

That will return category or product based on their controllers being CategoryController.php and ProductController.php respectively.

This does assume that you've not installed any third-party modules that rewrite those controllers with their own.

I am not a big fan of checking if the current_category registry exists, because basically any controller could do this and it wouldn't necessarily mean it's a category. My way of doing it is a bit more robust:

$fullActionName = Mage::app()->getFrontController()->getAction()->getFullActionName();
if ($fullActionName == 'catalog_category_view') { 
    ...  //Category
}
elseif ($fullActionName == 'catalog_product_view') {
    ...  //Product
}
Related