Magento: Recursive store category menu

This small chunk of code recursively outputs all (active) categories within a Magento store into a nested, clean, ordered list.

This is the perfect start to build your own category menu for your Magento based store. With some small modifications it's possible to only display the childs of the currently active category and attach something like class="active" to the corresponding link within this list.

<?php 
  $helper = $this->helper('catalog/category');
  $categories = $this->getStoreCategories();
  
  function printCategories($categories, $helper) {
    if( count($categories) > 0 ) {
      echo '<ul>';
        foreach( $categories as $category ) {
          echo '<li>';
          echo '  <a href="'.$helper->getCategoryUrl($category).'">'.$category->getName().'</a>';
          if ( count($category) > 0 ) {
            printCategories($category->getChildren(), $helper);
          }
          echo '</li>';
        }
      echo '</ul>';
    }
  }
  
  printCategories($categories, $helper);
?>

 

Add your comment

Please keep it polite and on topic. Your email address will not be published.

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)