Collection – Display Four Random Products on Homepage

cmscollection;product-collectionproduct-listrandom

I'm trying to get 4 random products on the homepage using PHP within a TPL file I've created. I'd like to be able to format the products in a foreach loop as I'm using some formatting in the code seen below…

<div class="three columns">
  <div class="product_container no_border">
    <div class="product">
      <a href="product_page.html"><img src="<?php echo $this->getSkinUrl('images/products/place_holder.jpg'); ?>" alt=" "></a>
    </div>

    <div class="product_title">
      <a href="product_page.html">240 Serving Package</a>
    </div>

    <div class="price_hp">$454.99</div>

    <div class="free_shipping">
      <div class="fs"></div>
      Free shipping for this package
    </div>

    <div class="shop_btn">
      <a href="#">ADD TO CART</a>
    </div>
  </div>
</div>

I've tried a few things found on Google but no luck yet. Setting categories in an array would certainly work for what I'm trying to do but it'd also work if the categories were random.

Thanks!

Best Answer

Try this. I worked for me:

$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect(array('name', 'thumbnail', 'price')); //feel free to add any other attribues you need.
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products); 
$products->getSelect()->order('RAND()');
$products->getSelect()->limit(4);
foreach ($products as $product)  : ?>

<div class="three columns">
  <div class="product_container no_border">
    <div class="product">
      <a href="<?php echo $product->getProductUrl()?>"><img src="<?php echo Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(100, 80)?>" alt=""></a>
    </div>

    <div class="product_title">
      <a href="<?php echo $product->getProductUrl()?>"><?php echo $product->getName()?></a>
    </div>

    <div class="price_hp"><?php echo Mage::app()->getStore()->getCurrentCurrency()->format($product->getFinalPrice());?></div>

    <div class="free_shipping">
      <div class="fs"></div>
      Free shipping for this package
    </div>

    <div class="shop_btn">
      <a href="<?php echo Mage::helper('checkout/cart')->getAddUrl($product)?>">ADD TO CART</a>
    </div>
  </div>
</div>
<?php 
endforeach;?>