1

I list the subcategories with this code

$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/>';
}

I want to show only first 3 subcategories. How can I do it?

1

3 Answers 3

5

Use

$collection
    // ->addFieldToFilter...
    ->setPageSize(20)
    ->setCurPage(1);
0
5

Try adding a limit to the collection.
And in addition you can get the root catalog id without hard coding it.
You also don't need all the root children ids. You can filter the collection by parent 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/>';
}
8
  • Hmmm...someone downvoted this right after I posted the answer. I don't think he even read the answer. Is this a rage down-vote? Anyway. I've tested this, and it works.
    – Marius
    Mar 26, 2014 at 9:07
  • 1
    Thanks for the +1s. I know who downvoted this. It is the guy that had an answer here, but deleted it. He thought I downvoted his answer (which I didn't) because I said it's not the best solution. Well...there are people and people.
    – Marius
    Mar 26, 2014 at 9:11
  • Actually I downvoted his answer and was explaining why in a long comment about php/mysql context switching, sql full table scans, sql memory usage, php memory usage. But he deleted his answer before I could complete my comment. It's a clear case of misdirected revenge downvote from dagerously oblivious developers. Mar 26, 2014 at 9:12
  • 2
    @MihaiStancu Then this was by accident. You should always drop a comment, give the person a chance to react on this, and then down-vote. not before. You can trust me that if there are good reasons, I'll change or delete my answer
    – hek2mgl
    Mar 26, 2014 at 9:14
  • 3
    I think that all 3 answers provided here are correct. (that's why I +1'd the other 2). I just took it up a notch and optimized the rest of the code.
    – Marius
    Mar 26, 2014 at 9:17
4

Use following

$collection= Mage::getModel('catalog/category')
->getCollection()
->setPageSize(3);
echo $collection->count();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.