Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if on product page programmatically in Magento

Tags:

php

magento

I want to insert tracking codes on all of the pages of a Magento site, and need to use a different syntax if the page is a CMS page, a category browsing page, or a product view page. I have a custom module set up with a block that inserts a generic tracking code on each page for now. From within the block, how can I distinguish between CMS pages, category pages, and product pages?

I started with:

Mage::app()->getRequest();

I can see that

Mage::app()->getRequest()->getParam('id');

returns the product or category ID on product and category pages, but doesn't distinguish between those page types.

Mage::app()->getRequest()->getRouteName();

return "cms" for CMS pages, but returns "catalog" for both category browsing and product view pages, so I can't use that to tell category and product pages apart.

Is there some indicator in the request I can use safely? Or is there a better way to accomplish my goal of different tracking codes for different page types?

like image 261
Del F Avatar asked Jun 14 '10 23:06

Del F


People also ask

How do you show products in Magento?

Easy Steps to Display Products in Magento 2 Home PageSelect the widget type as 'Catalog Products List' and enter the basic information. In the bottom you can see the conditions to add. Select the option 'Category' and select the category you want to display in home page and click “Insert Widget” button. That's it.


2 Answers

The easest answer is the following:

<?php
echo $this->getRequest()->getControllerName();
if($this->getRequest()->getControllerName()=='product') //do something
if($this->getRequest()->getControllerName()=='category') //do others
?>

this is 100% the right way to do according to the MVC model, please look into the core code really understand it, and do not give the method with loading or depends on the registry method. Support mytraining.net even though I am not there.

like image 57
bzhang Avatar answered Oct 12 '22 23:10

bzhang


There may be an even better way to do this using routers, but one fast way is to check the registry to see if we have a single product that we are looking at:

<?php

$onCatalog = false;
if(Mage::registry('current_product')) {
    $onCatalog = true;
}

Hope that helps!

Thanks, Joe

like image 30
Joe Mastey Avatar answered Oct 12 '22 23:10

Joe Mastey