Alternative Magento category tree structure
16 Oct 2009, by Denis Margetic
3 Comments · Posted in Magento

    The underlying issue is that the 'Default Category' is not easily accessible in code. For example, the default top navigation in Magento uses the getStoreCategories() method to access all categories. But that method starts by returning the 'Default Category' child categories and never returns the 'Default Category' itself. A solution to this is to add a subcategory, such as 'Products', under the 'Default Category' so that we can effectively treat the 'Products' category as the root of the category tree. Adding a 'Products' category means that any subsequent categories need to be subcategories of the 'Products' category. With this change the top level navigation will only show the 'Products' category. A sample category tree is shown below.

    Sample category tree

    Generally speaking, the primary reason for adding the 'Product' category is to enable direct access to the effective root category in code. One might want to add this flexibility, but still keep the usual behaviour for the top navigation. In that case the use of getStoreCategories() needs to be somewhat modified in:


    Any instance that looks as follows

    <?php foreach ($this->getStoreCategories() as $_category): ?>
    <?php endforeach ?>

    needs to be changed to

    <?php foreach ($this->getStoreCategories() as $default_category): ?>
     	<?php if ($default_category->getUrlKey() != 'products') { continue; } ?>
     	<?php foreach ($default_category->getChildren() as $_category): ?>
     	<?php endforeach; ?>
     <?php endforeach ?>

    With this change whatever code was in place of the ellipsis will still work without modification.

    A word of caution regarding Magento categories: In some circumstances, Magento can lose category associations in the backend - even though existing categories are still stored in the Magento database, the associations to those entries are lost. If this happens the Magento backend shows an empty category tree and the categories need to be added back in from scratch. As the associations are stored in the database, the safest approach is to backup the database before making any major changes to the category tree. If something does go wrong you can always revert to the backup and try again.

    Using this alternative category layout, you will be able to use all of the relevant store categories for navigation, as well as be able to access them in code. You can also make use of this structure for adding in sibling categories to 'Products' that can be used for featured products, specials, clearance items, and so on. Finally, this approach also makes it possible to browse all products using layered navigation by setting is_anchor = Yes on the new root category, something else which isn't possible using the default behaviour.