Reputation: 2221
I added a yes/no attribute on my products which would allow me to display recommended products (attribute is set to yes), on the front page. Now, I want to display 1 random product in my homepage. This is my code right now:
$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;
It's not that clean I know, it works but there are instances in which it doesn't return any products and instances in which it returns 2. How can I make this return 1 product at all times?
Upvotes: 0
Views: 578
Reputation: 4214
Try with $show_num_items = 1;
and $index_iterator = 0;
, and add ->addAttributeToFilter('recommend_product', 1);
to your collection
Upvotes: 2