Magento – display all and only direct children of a category

category

Say I have the following category and product structure:

    1. Category
        a. Subcategory
           i. Product
           ii. Product
        b. Subcategory
           i. Product
        c. Product
        d. Product

When viewing the category page, I want to show all and only its direct children. So, for this example, I would want to list a, b, c & d (but not a i., a ii., etc.).

I'm pretty new at Magento, so I'm having trouble stitching together a view that does what I want it to. So far, I have this:

<?php
$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
        ->addAttributeToSelect(array('name', 'thumbnail'))
        ->addAttributeToFilter('is_active', 1)
        ->addIdFilter($category->getChildren())
?>
<ul class="thumbnails featured category">
    <?php foreach ($categories as $category): ?>
        <li class="span 2">
            <a href="<?php echo $category->getUrl() ?>">
                <div class="thumbnail">
                <img src="<?php echo Mage::getBaseUrl('media') . 'catalog' . DS . 'category' . DS . $category->getThumbnail() ?>" alt="<?php echo $this->htmlEscape($category->getName()) ?>" />
                    <h5><?php echo $category->getName() ?></h5>
                </div>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

This will display the subcategories, but it won't display the products, if they are direct children. I don't really understand Magento's syntax yet, so I don't quite know what I'm doing here (I copied, adopted, and pasted this from elsewhere on the web).

Is there a way to generalize this list item to display the product thumbnail and url, if it's a direct child? Or, perhaps to create another list item that displays the product, on the condition that the direct child is a product, and not a subcategory?

Best Answer

To get the direct children of a category getChildern() function is there. It will return id of all direct children as string.

$category->getChildren();//this will return 2,3,4,5 (for example)

Then use php -> explode() function to get all these id as an array.