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.

Marius.