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

Delivering modern software? Atomist automates your software delivery experience.

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
}
?>


Start automating your delivery right there on your own laptop, today! Get the open source Atomist Software Delivery Machine.

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 }}