Tuesday, June 7, 2011

Add category names to the product list

In order to add category names to the product list (grid)
you have 2 options. For both of them you have to edit app/design/frontend/{interface}/{theme}/template/catalog/product/list.phtml
1. Add the category (categories) link(s) for all the products in any list (search results included). Keep in mind that any product can be in one or more categories (or none).
At the top of the file add this:
<?php $_category = Mage::regsitry('current_category');?>
<?php if ($_category) : ?>
<a href="<?php echo $_category->getUrl();?>"><?php echo $_category->getName();?></a>
<?php endif;?>
At the top of the file add this:
<?php $_categories = array();?>
This will work as some kind of cache.
Now below the $_product item (inside the foreach) add this
<?php foreach ($_product->getCategoryIds() as $categoryId) : ?>
 <?php if (isset($_categories[$categoryId])) : ?>
  <?php $_category = $_categories[$categoryId];?>
 <?php else:?>
  <?php $_category = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($categoryId);?>
  <?php $_categories[$categoryId] = $_category;?>
 <?php endif;?>
 <a href="<?php echo $_category->getUrl()?>"><?php echo $_category->getName();?></a>
 <?php //if you want only the first category link add a break here; ?>
<?php endforeach;?>
This second method covers all the cases but it's a little bit slower than the first one.


  1. Hi there,
    I read your blog and found you very knowledgeable on Magento. I've got a big problem with search component in Magento and would appreciate if you could help me on that. We have several simple products and more than 200 bundled products.
    when I search for a simple product in website, all the bundled products come to the search result. As I found the cause is that it search over the bundle items (options) too. Do you know how can I disable search over bundle items and make it for example just search over product's name and description.

  2. Hello Arash. Unfortunately I don't know how you can do this. I suspect it has something to do with the indexing process. Look in the CatalogSearch module, in the indexer model and see how it works and what it indexes.

    Sorry but I cannot do more.