Listing Subcategories on a Category Page in Magento

Listing Subcategories on a Category Page in Magento

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

Author: daharveyjr

I’m a solution architect responsible for the design, development, implementation, testing, and maintenance of e-commerce operations and applications using the Hybris and WebSphere Commerce product suites and other web technologies such as Java, J2EE/JEE, Spring, PHP, WordPress and more. Twitter | Facebook | Google+ | LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *