Magento: Show subcategories with images and products on category page.

The question was asked:

How do I sort products on a category page by subcategory as well as limit the number of products from each subcategory:

For example if the category was Food I would want to display the following:

Drinks:  Coke 12oz, Orange Juice 8oz, Milk Gallon,

Pasta:  Spaghetti 1lb, Pesto 12 pc, Tortellini 1 PC.

And so on, displaying each subcategory name followed 3 products (images etc.)

There are multiple locations you could use the following code, however, you have to have access to the current active category for this to work.

<!-- Finding Current Category and Finding it's children -->
$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
        ->addAttributeToSelect(array('name', 'thumbnail'))
        ->addAttributeToFilter('is_active', 1)
<div class="subcategories">
    <p>Select a category to view products:</p>
    <ul class="clearfix">
    <!-- Display Each Subcategory Image and Name  -->

    <?php foreach ($categories as $category): ?>
        <li class="grid12-3">
            <a href="<?php echo $category->getUrl() ?>" class="clearfix">
                <?php if($thumbFile = $category->getThumbnail()): ?>
                <img src="<?php echo Mage::getBaseUrl('media') . 'catalog' . DS . 'category' . DS . $thumbFile;?>" alt="<?php echo $this->htmlEscape($category->getName()) ?>" />
                <?php endif;?>
                <span><?php echo $category->getName() ?></span></a>
        <!-- Load (3) Products from within each subcategory  -->
        $_helper = $this->helper('catalog/output');
        $products = Mage::getModel('catalog/product')
            ->addAttributeToSelect(array('name', 'product_url', 'small_image'))
        <!-- Display Each product's detailed info  -->
        <?php foreach ($products as $product): ?>
            <?php // Product Image ?>
            <a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($product, 'small_image'), null, true) ?>" /></a>
            <?php // Product description ?>
            <?php $_productNameStripped = $this->stripTags($product->getName(), null, true); ?>
            <h2 class="product-name"><a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $productNameStripped; ?>"><?php echo $_helper->productAttribute($product, $product->getName() , 'name'); ?></a></h2>
        <?php endforeach ; ?>

    <?php endforeach; ?>
I commented within the code what I am doing within each step. Good luck, hope this helps!!

Leave a Reply