Magento - 循环多个类别ID

时间:2013-11-11 18:23:18

标签: php magento

我试图循环多个类别,因此用户在标题标记中插入如(2,43,11)它应该显示当前类别只抓取一个ID。有任何想法吗?谢谢!

循环代码:

<?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;?>

1 个答案:

答案 0 :(得分:2)

您很可能忘记在第一行中拆分类别ID。试试这个:

<?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;?>

但是,无论如何这是非常糟糕的编码风格,你需要将这些代码移动到单独的块并使用一些缓存来防止无用的重载。我不建议在生产中使用它。

一些建议,

  • 替换为 Mage :: getModel
  • 如果您使用类别集合(少数类别),则使用Mage :: getModel('catalog / category') - &gt; getCollection()并使用过滤器'in'过滤它(参见下面的示例)
  • 尽量避免使用addAttributeToSelect('*'),这是非常昂贵的操作(在资源使用的意义上)

这好一点

<?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 } } ?>

但看起来仍然很难看,因为它在模板中。这样的代码应该在块类中。