随机和限制主页magento上的类别拇指

时间:2013-01-21 14:34:32

标签: php magento random thumbnails categories

以下代码只显示“类别12”中所有子类别的类别大拇指,以寻找将此数字限制为6个类别并将其随机选择为这些类别的方法。

    <ul class="brand_list">
        <?php $media = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>
        <?php $children = Mage::getModel('catalog/category')->getCategories(12);   ?>
        <?php foreach ($children as $category): ?>
            <?php $category = Mage::getModel('catalog/category')->load($category->getId()); ?>
            <li class="span3">
                <a href="<?php echo $category->getUrl(); ?>">
                    <img alt="<?php echo $category->getName(); ?>" src="<?php echo $media; ?>/catalog/category/<?php echo $category->getThumbnail(); ?>" />
                </a>
            </li>
        <?php endforeach; ?>
    </ul>

之前我使用过类似代码的产品使用以下两段代码:

<?php $collection->getSelect()->order('rand()'); ?>

<?php $_columnCount = $this->getColumnCount(); ?>
<?php $i=0; foreach ($collection->getItems() as $category): if($i==6){break;}?>
<?php if ($i++%$_columnCount==0): ?> 
<?php endif ?>

我尝试重新编码以适应类别大拇指,但我似乎没有任何快乐。

1 个答案:

答案 0 :(得分:2)

您的问题的解决方案如下:我不会使用mysql rand()函数,因为它很慢。

<ul class="brand_list">
  <?php 
    $media = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
    $parentCategory = Mage::getModel('catalog/category')->load(12);
    $children = Mage::getModel('catalog/category')
                  ->getCollection()
                  ->addIdFilter( array_rand( array_flip( $parentCategory->getAllChildren( true ) ), 6) )
                  ->addAttributeToSelect('name')
                  ->addAttributeToSelect('thumbnail');
  ?>
  <?php foreach ($children as $category): ?>
    <li class="span3">
      <a href="<?php echo $category->getUrl(); ?>">
        <img alt="<?php echo $category->getName(); ?>" src="<?php echo $media; ?>catalog/category/<?php echo $category->getThumbnail(); ?>" />
      </a>
    </li>
  <?php endforeach; ?>
</ul>