You are viewing an old revision of this post, from January 13, 2016 @ 15:41:56. See below for differences between this version and the current revision.

Magento – DISPLAY CATEGORIES AND SUBCATEGORIES IN MAGENTO

Listing Categories in Magento 1.4.1.1 & Above

Firstly, you need to make sure the block that you're working is of the type catalog/navigation. If you're editing catalog/navigation/left.phtml then you should be okay. In my previous example, we used the Category model to load in category information. This can be slow and often loads in more information than we need for a simple navigation menu. This version uses the Varien_Data_Tree class.
<div id="leftnav">
    <?php $helper = $this->helper('catalog/category') ?>
    <?php $categories = $this->getStoreCategories() ?>
    <?php if (count($categories) > 0): ?>
        <ul id="leftnav-tree" class="level0">
            <?php foreach($categories as $category): ?>
                <li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
                    <a href="<?php echo $helper->getCategoryUrl($category) ?>"><span><?php echo $this->escapeHtml($category->getName()) ?></span></a>
                    <?php if ($this->isCategoryActive($category)): ?>
                        <?php $subcategories = $category->getChildren() ?>
                        <?php if (count($subcategories) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
                                <?php foreach($subcategories as $subcategory): ?>
                                    <li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
                                    </li>
                                <?php endforeach; ?>
                            </ul><script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
                        <?php endif; ?>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul><script type="text/javascript">decorateList('leftnav-tree', 'recursive')</script>
    <?php endif; ?>
</div>
If you copy and paste the above code into catalog/navigation/left.phtml, it should work straight away. It should list all categories and any first level subcategories of the current category. You can modify this code to display all sub-categories by removing the IF statement at line 9.

Revisions

  • January 13, 2016 @ 15:41:56 [Current Revision] by admin
  • January 13, 2016 @ 15:41:56 by admin

Revision Differences

There are no differences between the January 13, 2016 @ 15:41:56 revision and the current revision. (Maybe only post meta information was changed.)

No comments yet.

Leave a Reply