Display Random Products in Magento


I have explained the method for displaying random products below:


	//below code to written in file which extends the product block
	$collection = Mage::getResourceModel('catalog/product_collection');
        return parent::_beforeToHtml();     
  //below code to written in template file
        if (($_products = $this->getProductCollection())):
        	echo $_product->getSku();

You can extend the script further as per your requirement. This is a basic way of displaying random products in a page from the product catalog.

Hope it is helpful

40 Responses to “Display Random Products in Magento”

  1. Anne Maria says:

    Thanks for your help

  2. Pradeep says:

    i am using $this->_productCollection->getSelect()->order(‘rand()’); in
    protected function _getProductCollection() app/code/local/mage/catalog/product/list.php for getting products in randomly.

    but the problem is after adding this line some of the products are getting repeated.

    • You mean to say in the same collection, you are getting the products more than once ?

      • Pradeep says:

        yes,in that same collection i am getting the products more than once.

        • Could you paste the code here, the product collection contains unique products, please check whether multiple products have same names ?

          • Pradeep says:
            $this-&gt;_productCollection = $layer-&gt;getProductCollection();
            //i am adding below line $this-&gt;_productCollection-&gt;getSelect()-&gt;order('rand()'); 
          • I suggest you to print product ids from the product collection before and after applying the random function, to check the difference

          • Naim says:

            As you said “I suggest you to print product ids from the product collection before and after applying the random function, to check the difference”

            but please can give me the code how to apply random code correctly so that same product don’t show multiple times ? it will be better if you show to apply the code in app\code\core\Mage\Catalog\Block\Product\List\Toolbar.php

            if ($this->getCurrentOrder()) {
            if ($this->getCurrentOrder() == ‘random’) {
            else {
            $this->getCollection()->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());

            please let me know how to apply the product ids correctly so that each product appear only 1 item not multiple times in the the Catalog Page. Thanks

  3. Andy says:


    I need to get one random product of a specified category. The ‘status’ of the product must have 1.

    I tried to get the complete product list of the specified category, but there are so many products so the server needs a lot of time to deliver the complete list :(

    Thx, andy

  4. Wesley says:


    On my home page display only one row and three items for new item.

    I want to display 2 rows and random my new items.

    here is my website

    can you help me please?

    Please tell me which file should i modify and code, i just start learning Magento.

    Thank so much

    • Pragnesh says:

      You need to add limit to the collection (for 6 products) refer Limit results collection in Magento and apply the random filter to this collection, hope this is helpful

      • wesley says:

        Thank for your help.
        Which file should i add this code?

        getCollection()->setOrder(‘name’, ‘asc’); //getting the product collection, results are ordered by product name
        $product_collection->getSelect()->limit($limit,$starting_from); //where $limit will be the number of results we want, $starting_from will be the index of the result set to be considered as starting point (note 0 is the index of first row)
        //this will ouptput 6 records starting from 3rd record
        foreach($product_collection as $_product)
        echo $_product->getName().”;

  5. Wesley says:

    Dear sir / madam,

    I have a website using magento
    How can i display random product in my product list page base on category? in my category i have a lot of products and different type.

    I look through your code, I want to try but i don’t know which file i need to edit?
    can you give me the part of file that i need to modify please?

    Thank a lot

    • Pragnesh says:

      The product listing page has already category filter applied, check the code at app/code/core/Mage/Catalog/Block/Product/List.php, you simply need to add the random filter here ‘$layer->getSelect()->order(‘rand()’);’

      • Wesley says:

        I got it now, thank for your code it works perfect.

      • peter says:

        hello i stumbled on your post will searching for how to make my products load randomly.forgive my question for i am not a programmer. where should i insert the code on list.php? is there a particular position should i just past paste like that?

        • Pragnesh says:

          You can place the code in the block you are extending, you can refer the comments I have explained in detail

          • peter says:

            i checked the list.php file and got this

            $origCategory = null;
            if ($this->getCategoryId()) {
            $category = Mage::getModel(‘catalog/category’)->load($this->getCategoryId());
            if ($category->getId()) {
            $origCategory = $layer->getCurrentCategory();
            $this->_productCollection = $layer->getProductCollection();


            if ($origCategory) {

            return $this->_productCollection;

            where should i add the random filter?

          • Pragnesh says:

            Mailed you the details

  6. Hans says:

    Thanks for the code. It works great, but i want to call ONLY products which have SPECIAL PRICES ! Do you also have a solution for it?

    Best regards

    • Pragnesh says:
      $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
      foreach($collection as $product)
      	$price = $product->getFinalPrice();
      	if($price > 0)
      		echo $product->getName();
  7. sunil says:

    i want only upsell product randomly.tell me

    • Pragnesh says:

      you can use the rand() function on any magento collection

      • sunil says:

        i want only upsell product randomly.tell me

        • Pragnesh says:
          $object = Mage::getModel('catalog/product'); 
          $_product = $object->load($product_id); //Get product detail using product id   
          $upsell_product = $_product->getUpSellProductCollection(); //get up-sell product collection in magento
          $upsell_product->getSelect()->order('rand()'); //apply random order
           $count = count($upsell_product); 
           if(empty($count)) : 
                 //if empty
                 echo "No Records";
               //if result is not empty
                foreach($upsell_product as $_upsell):
  8. Nirmaan says:

    Here you will find the step by step solution .
    Display random products at homepage

  9. If you need filter the randon results by category is necessary change the file:


    _productCollection)) {
    $categoryID = $this->getCategoryId();
    $category = new Mage_Catalog_Model_Category();
    $category->load($categoryID); // this is category id
    $collection = $category->getProductCollection();
    } else
    $collection = Mage::getResourceModel(‘catalog/product_collection’);
    $numProducts = $this->getNumProducts() ? $this->getNumProducts() : 3;
    $collection->setPage(1, $numProducts)->load();

    $this->_productCollection = $collection;
    return $this->_productCollection;

  10. tuba says:

    Thank you for the code!

    I have got another code from a site, then modified and used in a .phtml file, named list_home.phtml

    Cms code:
    {{block type=”catalog/product_list” category_id=”50″ template=”catalog/product/list_home.phtml”}}


    $categoryID = $this->category_id;
    //$categoryID = $this->getCategoryId();
      $category = new Mage_Catalog_Model_Category();
      $category->load($categoryID); // this is category id
      $collection = $category->getProductCollection();
    } else{
      $collection = Mage::getResourceModel('catalog/product_collection');
    $numProducts = $this->getNumProducts() ? $this->getNumProducts() : 1;
    $collection->setPage(1, $numProducts)->load();
    $_productCollection = $this->_productCollection = $collection;
    <?php if(!$_productCollection->count()): ?>
    <div class="note-msg">
        <?php echo $this->__('There are no products matching the selection. Please provide a category ID.') ?>
    <?php else: ?>
    	<?php $_collectionSize = $_productCollection->count() ?>
        <?php foreach ($_productCollection as $_product): ?>		        
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>">
                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(105, 105); ?>" width="105" height="105" alt="<?php echo $this->htmlEscape($_product->getName()) ?>" />
        <?php endforeach ?>
    <?php endif; ?>
  11. Oliver Schmidt says:

    Hey nice for the code. But unfortunately i have no idea where to use it….
    Could you maybe give me a brief description what to do with it :)

    Thans a lot!

    • Pragnesh says:

      There are two parts written here.

      a) The code starting below this “//below code to written in file which extends the product block” should be written in file with php extension, file extending the product block

      b) The code starting below this “//below code to written in template file” shold be wriiten in file with phtml extension, that is template files.

      Kindly refer the Magento Product module for further explanation

Leave a Reply