Tuesday, November 23, 2010

Magento - Display Categories (with category images) in the homepage



<div class="top-home-category">
<?php 
/******** Don't know why I commented this
$_helper = $this->helper('catalog/output');
$_category = $this->getCurrentCategory();
$_imgHtml = '';

if ($_imgUrl = $_category->getImageUrl()) {
$_imgHtml = '<p class="category-image"><img src="'.$_imgUrl.'" alt="'.$this->htmlEscape($_category->getName()).'" title="'.$this->htmlEscape($_category->getName()).'" /></p>';
$_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
}
****************************************/
?>

<?php // Iterate all categories in store
 $limit = 0;
$_helper    = $this->helper('catalog/output');
foreach ($this->getStoreCategories() as $_category): 
// If category is Active
if($_category->getIsActive()):
// Load the actual category object for this category
$cur_category = Mage::getModel('catalog/category')->load($_category->getId());
if ($_imgUrl = $cur_category->getImageUrl()){
$_imgHtml = '<img src="'.$_imgUrl.'" alt="'.$this->htmlEscape($cur_category->getName()).'" title="'.$this->htmlEscape($cur_category->getName()).'"  width="105px" />';
$_imgHtml = $_helper->categoryAttribute($cur_category, $_imgHtml, 'image');
} 
?>
<div class="home-category">
<div class="linkimage">
<a href="<?php echo $this->getCategoryUrl($cur_category) ?>" style="border:none">
<?php echo $_imgHtml; ?>
</a>
</div>
<div class="category-link-container">
<a href="<?php echo $this->getCategoryUrl($cur_category) ?>">
<?php echo $_helper->categoryAttribute($cur_category, $cur_category->getName(), 'name') ?>
</a>
</div>
</div>

// Load a random product from this category
/*$products = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($cur_category)->addAttributeToSelect('small_image');
$products->getSelect()->order(new Zend_Db_Expr('RAND()'))->limit(1);
$products->load();
// This a bit of a fudge - there's only one element in the collection
$_product = null;
foreach ( $products as $_product ) {}
?>
<div class="home-category">
<div class="linkimage"><p><a href="<?php echo $this->getCategoryUrl($_category)?>">
<?php
if(isset($_product)):
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135, 135); ?>" width="135" height="135" alt="<?php echo $this->htmlEscape($_product->getName()) ?>" />
<?php
endif;
?> </a></p>
</div>
<a href="<?php echo $this->getCategoryUrl($_category)?>"><?php echo $_category->getName()?></a>
</div>
*/?> <?php
$limit+=1;
endif;
if ($limit==8):
break;
endif;
endforeach;
?> 
</div>

No comments:

Post a Comment