Magento 1 – How to Show Random Products from a Category

categorymagento-1productrandom

On my cart page i have a little display, which shows products from a certain category, it displays 4 products, but in my category i have 8-10 products. How can i make it select random products so it changes every time the page is refreshed.

This is my code for the products at the moment

<?php if (Mage::helper('checkout/cart')->getQuote()->getSubtotal() < 75.00)
{?>
 <h1><?php echo 'We see your subtotal is under £75, why not add these products to qualify for Free Delivery';?></h1>
 <br>
<?php

$categoryid = 1060;

$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
?>
<div class="upsell_products">

<?php foreach ($collection as $_product) { ?>


<div class="product">
<a href="<?php echo $_product->getProductUrl() ?>">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image'); ?>" alt="" /></a>
<a href="<?php echo $_product->getProductUrl(); ?>">
<p class="upsell_pro_name"><?php echo $_product->getName(); ?></p>
<p class="upsell_pro_price"><?php echo Mage::helper('core')->formatPrice($_product->getPrice());?></a></p>

</div>
<?php } }

If you can help thank you 🙂

Best Answer

Try using:

$categoryid = 1060;
$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSort()
    ->addAttributeToSelect('*')
    ->addCategoryFilter(Mage::getModel('catalog/category')->load($categoryid));
$products->getSelect()->order(new Zend_Db_Expr('RAND()'));

Source here.

Probably putting this after your load code might work too:

$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));