Monday, December 5, 2011

Add category names in product view page

Here is an other short but useful for some people thing you can do in Magento.
Here is how you can add the category tree path in the product view page.

Edit file app/design/frontend/{interface}/{theme}/template/catalog/product/view.phtml

And in the section that you want the categories to appear add this code:
<?php $categoryIds = $_product->getCategoryIds();?>
 <?php foreach ($categoryIds as $categoryId) :?>
  <?php $tmpId = $categoryId;?>
  <?php $categories = array();?>
  <?php while($tmpId != Mage::app()->getStore()->getRootCategoryId()) : ?>
   <?php $category = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($tmpId);?>
   <?php $categories[] = $category;?>
   <?php $tmpId = $category->getParentId();?>
  <?php endwhile;?>
  <?php for ($i = count($categories) - 1; $i>=0;$i--) :?>
   <a href="<?php echo $categories[$i]->getUrl() ?>"><?php echo $categories[$i]->getName() ?></a>
   <?php if ($i >0 ):?>
    -&gt;<!-- this is the tree separator. change to whatever you like-->
   <?php endif;?>
  <?php endfor;?>
  <br />
  <?php //break;//uncomment this if you want only one category tree to appear.?>
 <?php endforeach;?>

I hope this helps someone.
Keep in mind that this will make your page load a little slower, but I don't think it's something you should worry about.
Any comments are welcomed.



  1. Yes, this is true. I would say that some of your code should go in the Block portion of the MVC model rather than the actual View (phtml file). But overall it works. Thank you!

  2. I agree with you. But if I would have created blocks or modified them it wouldn't have been so easy to integrate.

  3. After a created blocks or a modified them than it's not easy to integrate with it..

    Magento Modules