我需要显示父类别中的4个随机子类别。
我有以下代码,它使用随机产品图像显示所需父类别(ID = 4)的所有子类别: list.phtml \应用\设计\前端\ MyTheme的\默认\模板\目录\类别
<?php
//迭代商店中的所有类别 foreach($ this-&gt; 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; ?&GT;
并在navigation.php中 \应用\代码\本地\法师\目录\块
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;
}
如何将子类别限制为4并随机显示?谢谢!
答案 0 :(得分:1)
要限制集合,您可以添加以下内容:
$collection->setPageSize(4);
要使您返回的记录随机化,这是其中一种可能性:
$collection->getSelect()
->order('rand()');