Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Listing Subcategories on a Category Page in Magento

DZone's Guide to

Listing Subcategories on a Category Page in Magento

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

I recently was working on a Magento Commerce website for a client that wanted to display all of the subcategories of a category on the category page, to improve basic navigation, and to further enhance and show the range of products that they carried.

The following code snippet was used to pull the child categories from the category object on the category page, and retrieve the necessary information for display. It retrieves the child categories from the category object (in the form of a comma-delimited string) using the getChildren() method, explodes them into an array, and iterates over that array, retrieving the category object for each subcategory ID identified. If the subcategory is marked as an acive category, the category name, thumbnail, and URL are then retrieved and displayed on the page as needed.

NOTE: The client’s HTML structure and code has been removed from the snippet; however, the code snippet still provides an appropriate example to retrieve and display child categories.

<?php
$_subcategories = $_category->getChildren();
if ($_subcategories && trim($_subcategories) != '') {
    $_subcategory_ids = explode(',', $_subcategories);
    ?>
    foreach($_subcategory_ids as $_subcategory_id): ?>
        <?php $_subcategory = Mage::getModel('catalog/category')->load($_subcategory_id); ?>
        if ($_subcategory->getIsActive()): ?>
            <?php if ($_subcategory->getThumbnail()): ?>
                <a href="<?php echo $_subcategory->getUrl(); ?>"><img src="<?php echo $_subcategory->getThumbnail(); ?>" /></a>
            <?php endif; ?>
            <a href="<?php echo $_subcategory->getUrl(); ?>"><?php echo $_subcategory->getName(); ?></a>
        <?php
        endif;
        ?>
    <?php
    endforeach;
    ?>
<?php
}
?>


BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}