search
top

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 Responses to “Display Random Products in Magento”

  1. Anne Maria says:

    Thanks for your help

  2. Pradeep says:

    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.

    • 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’) {
            $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

  3. Andy says:

    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

  4. Wesley says:

    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

    • 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 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

    • 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:

        Hi,
        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();
            $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?

          • 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('*');
      $collection->getSelect()->order('rand()');
      $collection->addStoreFilter();    
      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
          $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;   
          
  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:
    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;
    }
    }

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

    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; ?>
    
  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

top