test
test

Reputation: 2466

Magento - Loop multiple category ID

Im trying to loop multiple categories, so user insert like (2,43,11) in header tag it should show that categories currently it grabs only one ID. Any ideas? thanks!

loop code:

<?php $currentID = Mage::getSingleton('cms/page')->getContentHeading(); ?>
<?php if($currentID): ?>
<?php

$categoryid = $currentID;

$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');

foreach ($collection as $_product) { ?>

<li>

</li>

<?php } ?>
<?php endif;?>

Upvotes: 0

Views: 986

Answers (1)

Sergey Kolodyazhnyy
Sergey Kolodyazhnyy

Reputation: 691

Most likely you forgot to split category ids in the first line. Try this:

<?php $currentID = explode(',', Mage::getSingleton('cms/page')->getContentHeading()); ?>
<?php foreach($currentID as categoryid): ?>
<?php

$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');

foreach ($collection as $_product) { ?>

<li>

</li>

<?php } ?>
<?php endforeach;?>

But, anyway this is really bad style of coding, you need to move such code to separate block and use some cache to prevent useless overload. I don't recommend to use it on production.

Some recommendations,

  • Replace new with Mage::getModel
  • If you using category collection (few categories) it make a sense to use Mage::getModel('catalog/category')->getCollection() and filter it using filter 'in' (see example below)
  • Try to avoid using addAttributeToSelect('*'), it's quite expensive operation (in the meaning of resource usage)

This a bit better

<?php 
     $ids = explode(',', Mage::getSingleton('cms/page')->getContentHeading()); 
     $categories = Mage::getModel('catalog/category')->getCollection()
         ->addAttributeToFilter('entity_id', array('in' => $ids));

     foreach($categories as $category) {
        $collection = $category->getProductCollection();
        $collection->addAttributeToSelect('needed_attribute_code');
        foreach ($collection as $_product) { 
?>
         <li>

         </li>

<?php } } ?>

But still looks ugly, because it's in template. Such code should be in block class.

Upvotes: 2

Related Questions