I need to display 4 random subcategories from a parent category.
I have the following code, that displays ALL subcategories from the needed parent category (ID=4) with random product images: list.phtml \app\design\frontend\MYTHEME\default\template\catalog\category
<?php
// Iterate all categories in store foreach ($this->getChildCategories(4) as $_childCategory):
// If category is Active
if($_childCategory->getIsActive()):
// Load the actual category object for this category
$cur_category = Mage::getModel('catalog/category')->load($_childCategory->getId());
// 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 style="float: left; padding-right: 30px; text-align: center;">
<div class="linkimage"><p><a href="<?php echo $this->getCategoryUrl($_childCategory)?>">
<?php
if(isset($_product)):
?>
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135, 135); ?>" alt="<?php echo $_childCategory->getName()?>" title="<?php echo $_childCategory->getName()?>" />
<?php
endif;
?>
</div>
<?php echo $_childCategory->getName()?></a></p>
</div>
<?php
endif;
endforeach; ?>
and in navigation.php \app\code\local\Mage\Catalog\Block
public function getChildCategories($categoryId) //inserted for random subcategories on category page
{
$category = Mage::getModel('catalog/category');
if($category->checkId($categoryId) === false) {
return false;
}
$layer = Mage::getSingleton('catalog/layer');
$category->load($categoryId);
$layer->setCurrentCategory($category);
/* @var $category Mage_Catalog_Model_Category */
$collection = Mage::getModel('catalog/category')->getCollection();
/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
$collection->addAttributeToSelect('url_key')
->addAttributeToSelect('name')
->addAttributeToSelect('is_anchor')
->addAttributeToFilter('is_active', 1)
->addIdFilter($category->getChildren())
->joinUrlRewrite()
->load();
//$productCollection = Mage::getResourceModel('catalog/product_collection');
//$layer->prepareProductCollection($productCollection);
//$productCollection->addCountToCategories($collection);
return $collection;
}
How can I limit the subcategories to 4 and display them randomly? Thanks!