I'm displaying a list of sub categories by parent category ID and am wanting to display the category image in place of a category name.
Here is what I have so far...
<div id="menu_brands">
<div class="brand_head">
<h3><?php echo $this->__('Browse By Brand') ?></h3>
</div>
<div class="brand_list">
<?php
$cats = Mage::getModel('catalog/category')->load(6)->getChildren();
$catIds = explode(',',$cats);
$categories = array();
foreach($catIds as $catId) {
$category = Mage::getModel('catalog/category')->load($catId);
$categories[$category->getName()] = $category->getUrl();
$img = $category->getImageUrl(); //I suspect this line is wrong
}
ksort($categories, SORT_STRING);
?>
<ul>
<?php foreach($categories as $name => $url): ?>
<li>
<!--<a href="<?php echo $url; ?>"><?php echo $name; ?></a>-->
<a href="<?php echo $url; ?>" title="<?php echo $name; ?>">
<img src="<?php echo $img; ?>" width="auto" alt="<?php echo $name; ?>" /> <!--I suspect this line is wrong-->
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
I've tried countless ways to display the images in place of the category names but nothing seems to make the images appear. Currently with the above, the output is an empty 'img src' so there is clearly an error with what I'm trying (and probably a better way of achieving what I'm after).
Please could someone kindly point out what the problem is?
If it's of any relevance, what I intend to do afterwards is then display the category images in a grid format (3 or 4 per line).
Many thanks in advance.
The solution by zigojacko is not ideal because it separately loads in models in a loop. This does not scale well, and with many categories will thrash your database. Ideally, you'd add the images to the child collection.
A faster solution is to add the image attribute to a collection with an ID filter like B00MER:
// Gets all sub categories of parent category 'Brands'
$parent = Mage::getModel('catalog/category')->load(6);
// Create category collection for children
$childrenCollection = $parent->getCollection();
// Only get child categories of parent cat
$childrenCollection->addIdFilter($parent->getChildren());
// Only get active categories
$childrenCollection->addAttributeToFilter('is_active', 1);
// Add base attributes
$childrenCollection->addAttributeToSelect('url_key')
->addAttributeToSelect('name')
->addAttributeToSelect('all_children')
->addAttributeToSelect('is_anchor')
->setOrder('position', Varien_Db_Select::SQL_ASC)
->joinUrlRewrite();
// ADD IMAGE ATTRIBUTE
$childrenCollection->addAttributeToSelect('image');
?>
<ul>
<?php foreach($childrenCollection as $cat): ?>
<li>
<a href="<?php echo $cat->getURL(); ?>" title="<?php echo $cat->getName(); ?>">
<img class="cat-image" src="<?php echo $cat->getImageUrl(); ?>" />
</a>
</li>
<?php endforeach; ?>
</ul>