Magento - 循环多个类别 ID


Magento - Loop multiple category ID

我试图循环多个类别,因此用户在标题标签中插入类似(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;?>
很可能

您忘记在第一行拆分类别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;?>

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

一些建议,

  • new 替换为 Mage::getModel
  • 如果您使用类别集合(少数类别),则使用 Mage::getModel('catalog/category')->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 } } ?>

但仍然看起来很丑,因为它在模板中。此类代码应位于块类中。