我在我的产品上添加了一个yes/no属性,这将允许我在首页上显示推荐的产品(属性设置为yes)。现在,我想在我的主页上随机显示一个产品。这是我现在的代码:
$show_num_items = 2;
$show_index_array = array();
$index_iterator = 1;
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('type_id', 'configurable');
if($_productCollection->getSize()):
$show_index_array = range(0,($_productCollection->getSize()-1));
shuffle($show_index_array);
$show_index_array = array_slice($show_index_array, 0, $show_num_items);
foreach($_productCollection as $_product):
$_recommended = $_product->getData('recommend_product');
if($_recommended == 1):
if(in_array($index_iterator, $show_index_array)): ?>
<div><img src="<?php echo $this->helper('catalog/image')->init($_product, 'image'); ?>" />
</div>
<dl>
<dt><a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?></a></dt>
<dd><?php echo $_product->getResource()->getAttribute('short_description')->getFrontend()->getValue($_product); ?></dd>
<dd><a href="<?php echo $_product->getProductUrl(); ?>">Read More</a></dd>
</dl>
<?php endif;
$index_iterator++;
endif;
endforeach;
endif;
据我所知,它并没有那么干净,它是有效的,但在某些情况下,它不返回任何产品,在某些情况中,它返回2。我如何在任何时候都能退货1件产品?
尝试使用$show_num_items = 1;
和$index_iterator = 0;
,并将->addAttributeToFilter('recommend_product', 1);
添加到您的集合