Display Random Products in Magento

Hello,

I have explained the method for displaying random products below:

<?php	

	//below code to written in file which extends the product block
	$collection = Mage::getResourceModel('catalog/product_collection');
        Mage::getModel('catalog/layer')->prepareProductCollection($collection);
        $collection->getSelect()->order('rand()');
        $collection->addStoreFilter();       
        $this->setProductCollection($collection);
        return parent::_beforeToHtml();     
        
?> 
  //below code to written in template file
        
        if (($_products = $this->getProductCollection())):
        	echo $_product->getSku();
        endif;

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 thoughts on “Display Random Products in Magento

  1. Hi,
    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.

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

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

    4. 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’) {
      $this->getCollection()->getSelect()->order(‘rand()’);
      }
      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

  2. Hi!

    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

  3. hi

    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 http://www.lafindings.com

    can you help me please?

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

    Thank so much

    1. 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().”;
      }
      ?>

    2. You can directly edit the product block, or you can add in your custom block or view file. It depends on which module you are using.

    3. Honestly, i don’t know which file name to display my new items on homepage.

      Right now it display only three items and only one row.

      Can you guide me more detail please?
      I really thank for your help.

    4. which page is product blog page?
      honestly i don’t know which file is my new product page that show on my home page.
      can you guide more please?

      thanks

  4. Dear sir / madam,

    I have a website using magento 1.7.0.2
    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

    1. 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()’);’

    2. 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?

    3. 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();
      $layer->setCurrentCategory($category);
      $this->addModelTags($category);
      }
      }
      $this->_productCollection = $layer->getProductCollection();

      $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

      if ($origCategory) {
      $layer->setCurrentCategory($origCategory);
      }
      }

      return $this->_productCollection;
      }

      where should i add the random filter?

  5. 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

    1. $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
      $collection->getSelect()->order('rand()');
      $collection->addStoreFilter();    
      foreach($collection as $product)
      {
      	$price = $product->getFinalPrice();
      	if($price > 0)
      	{	
      		echo $product->getName();
      
      	}
      }
      
    1. $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
      $upsell_product->addStoreFilter();
       $count = count($upsell_product); 
       if(empty($count)) : 
             //if empty
             echo "No Records";
       else:
           //if result is not empty
            foreach($upsell_product as $_upsell):
              print_r($_upsell->getData());
            endforeach;
      endif;   
      
  6. If you need filter the randon results by category is necessary change the file:
    app\code\core\Mage\Catalog\Block\Product\List\Random.php

    to:

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

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

  7. 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”}}

    Code:

    <?php
    $_productCollection=$this->getLoadedProductCollection();
    $categoryID = $this->category_id;
    //$categoryID = $this->getCategoryId();
    if($categoryID){
      $category = new Mage_Catalog_Model_Category();
      $category->load($categoryID); // this is category id
      $collection = $category->getProductCollection();
    } else{
      $collection = Mage::getResourceModel('catalog/product_collection');
    }
    Mage::getModel('catalog/layer')->prepareProductCollection($collection);
    $collection->getSelect()->order('rand()');
    $collection->addStoreFilter();
    $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.') ?>
    </div>
    <?php else: ?>
      <ul>
    	<?php $_collectionSize = $_productCollection->count() ?>
        <?php foreach ($_productCollection as $_product): ?>		        
    		<li>
            <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()) ?>" />
            </a>
    		</li>
        <?php endforeach ?>
    </ul>
    <?php endif; ?>
    
  8. 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!

    1. 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

Your email address will not be published. Required fields are marked *

Scroll to top