Friday, 15 June 2012

Display sub-categories on category page



First create a new phtml file and save it in your/app/design/frontend/default/yourTheme/template/catalog/category folder.


1-     we have to find the category id for the page we're looking at. (This code will only be called when we're on a category page). We find the id with the following code:

//get the current category
$_cat = new Mage_Catalog_Block_Navigation();
$currentCat = $_cat->getCurrentCategory();

              
2-    This gives us the current category, in the next step we'll use its id to find the sub categories (children) associated with it.

//get the children of the current category
$subCats = Mage::getModel('catalog/category')
              ->load($currentCat->getId())->getChildren();

                              
                              
3-    $subCats now contains a comma separated list of the ids of the sub categories. We need to get rid of the commas:

//get sub category ids
$subCatIds = explode(',',$subCats);
                              
4-    Now the last step is-

<?php if (count($subCatIds) > 1): ?>
 <ul>
  <?php foreach($subCatIds as $subCatId): ?>
   <?php $subCat = Mage::getModel('catalog/category')->load($subCatId); ?>
               <?php if($subCat->getIsActive()): ?>
                <li>
      <?php //display category image
                 if($subCat->getImageUrl()): ?>
                  <img src="<?php echo $subCat->getImageUrl(); ?>" />
                 <?php endif; ?>
                 <a href="<?php echo $subCat->getUrl(); ?>">
                 <?php echo $subCat->getName(); ?>
                 </a>
                </li>
               <?php endif; ?>
   <?php endforeach; ?>
  </ul>
<?php endif; ?>


1 comment:

  1. Thanks for the post ma'am..

    But there must be one correction(suggestion):

    There should be <?php if (count($subCatIds) > 0): ?>

    in place of

    <?php if (count($subCatIds) > 1): ?>

    Any way.. thanks again.. it saved my time.. :)

    ReplyDelete