我用这段代码列出了子类别
$root = Mage::getModel('catalog/category')->load(3); // Put your category ID here.
$subCat = explode(',',$root->getChildren());
$collection = $root->getCollection()->addAttributeToSelect("*")->addFieldToFilter("entity_id", array("in", $subCat) );
foreach($collection as $subcategory) {
echo '<a href="'.$subcategory->getURL() .'" />» '.$subcategory->getName().'</a><br/>';
}
Run Code Online (Sandbox Code Playgroud)
我想只显示前3个子类别.我该怎么做?
使用
$collection
// ->addFieldToFilter...
->setPageSize(20)
->setCurPage(1);
Run Code Online (Sandbox Code Playgroud)
尝试为集合添加限制.
此外,您可以获得根目录ID而无需对其进行硬编码.
您也不需要所有root子ID.您可以按父ID过滤集合.
$rootId = Mage::app()->getStore()->getRootCategoryId();
$collection = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect("*")
->addFieldToFilter("parent_id", $rootId);
$collection->addAttributeToSort('position'); //sort by position
$collection->setPage(1, 3);//limit 3, page 1
foreach($collection as $subcategory) {
echo '<a href="'.$subcategory->getURL() .'" />» '.$subcategory->getName().'</a><br/>';
}
Run Code Online (Sandbox Code Playgroud)