Dx3webs : The Ultimate Magento Host - Speed : Support : Security

Dx3webs is the ULTIMATE Magento host with a wide range of options for businesses of all sizes.
magento-logo

How to create a Random Featured Product list on home page in Magento

[stextbox id="custom" color="ffffff" bcolor="ffffff'" bgcolor="000000" image="null" float="true" width="600"]
It seems some what amazing that such a simple request can be so tricky to track down. The scenario is simple. You want to display a set of products on your home page from a hidden category to be randomly displayed.
[/stextbox]

If you want to show products from a specific category on your home page you can do this simply with

[php]
{{block type="catalog/product_list" category_id="12" template="catalog/product/list.phtml"}}
[/php]

on your home page which works fine.. however, if you want these products to be randomly selected you hit problems.

The obvious thing to try is

[php]
{{block type="catalog/product_list_random" category_id="12" template="catalog/product/list.phtml"}}
[/php]

however, this displays random products from EVERY category!!

The reason for this is that the file random.php does not work as advertised so we need to create a new version that does. We do not want to break upgrade compatibility so create the following directory structure.

in app/code/local create Mage/Catalog/Block/Product/List

eg mkdir -p Mage/Catalog/Block/Product/List

In your new List directory create the following file called Random.php

[php]
<?php
class Mage_Catalog_Block_Product_List_Random extends Mage_Catalog_Block_Product_List
{
protected function _getProductCollection()
{
if (is_null($this->_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;
}
}
[/php]

To call this on your home page open your Home page in CMS > Static Pages

and in Content add

[php]
{{block type="catalog/product_list_random" category_id="YOUR_CATEGORY_ID" template="catalog/product/list.phtml" column_count="4" num_products="12"}}
[/php]

Create a new hidden category and add the products you wish to randomly select from. Find the category ID of this category and enter this number in the above place marker.

You will find that although you are seeing the Category display tool bar (drid view / list view / show.. etc) it has no effect on the layout. the default layout is 3 x 3 grid which is where column_count=”4″ comes into play. Alter this to meet your themes needs. Same goes for num_products=”12″.

And that is that.

Don’t want to be looking at the grid.. hide it. (evil hack alert)

Add

[css]
<style type="text/css">
.toolbar {display:none;}
</style>
[/css]

at the top of your Content area on the homepage CMS. this will hide the tool bar for just the homepage.
References:
Thanks to mac75a here : http://www.magentocommerce.com/boards/viewthread/72319/ and andytm here: http://www.magentocommerce.com/boards/viewthread/72319/

[stextbox id="alert" width="600" color="000" bcolor="000" bgcolor="eeeeee" image="null" caption="Looking for Optimised UK Magento Hosting"]
Rock solid speed and reliability
Robust, reliable, fully backed up, secure UK based Magento hosting for £175 per year. Full details here or Contact us
[/stextbox]

Tags: , , , , , , , , , , , ,

38 Comments : Leave a Reply

  1. Vinko says:

    This is a great addition to the Home page, but if the feature also take into account the product’s Visibility flag and whether the product is Enable that will be even better.

    Don’t you think?

  2. diglin says:

    @Vinko: the product’s visibility Flag is done by the method Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection)

    Thanks for the help of the whole community.

    If I were you I will overwrite too the method _beforeToHtml() with the following lines, no more problem with the toolbar.

    class Mage_Catalog_Block_Product_List_Random extends Mage_Catalog_Block_Product_List{
    protected function _beforeToHtml()
    {
    return $this;
    }

    }

  3. mptorr says:

    i’ve been unsuccessful in implementing this method to generate random upsell products pulled from the category of the product currently being visualized.

    any ideas how to achieve this?

  4. Marcos says:

    The trick to hide toobar doesn’t work in 1.3.2.3?

  5. admin says:

    If you edit in wysiwyg mode it will remove the tag

    as a precaution set the wysiwig mode to off by default… its a pain anyway :)

  6. Hi..
    I tried using this its nice.. but when my store is using pound as its currency why is it displaying “$” currency on home page for random products and pound on all rest of the pages.

  7. Azmi says:

    This worked great for my requirement… thanks.

  8. Jeroen says:

    Hi thanks for this.
    I run in a problem, instead off showing the selected category.
    It shows all the products random, hope you can help.

    Running version: 1.4.1.0

  9. mlclm says:

    Great solution. So far it’s working, I the 3 products showing up randomly each time I refresh the homepage.

    In order to have 3 products instead of 4, I changed (line 35):

    Now I need to figure out why there aren’t any images for the products because right now, no images are showing up. Any working solution for that problem?

    Also I wanted to know, what is $_collectionSize for? (line 7)

    Thanks!

    ps- Great blog btw, very useful.

  10. mlclm says:

    ok, everything works fine, I’ve managed to make the products images appear. Thanks again for this solution!

  11. admin says:

    Glad you got it sorted. Thanks for the feedback.

  12. will says:

    i’m using your random.php code, but i still think it is calling all the products from every category?

  13. Will says:

    i want to display all products from the current category in product view page, right now by using random.php, i can only display random products from every category in my product page, do you know how to modify the random.php file to make it just collect the current category products?

  14. admin says:

    have you specified

    category_id=”12″

    in you block call?

  15. Jörgen says:

    Cant seem to get it to work looks like it loads all the products..

  16. Jörgen says:

    Nvm works now..

    To hide the toolbar in later versions use

    .pager {display:none;}

  17. admin says:

    Nice one did you figure out what the problem was?

  18. Aureh says:

    For me the same.
    It loads all the products and doesn’t filter on the specified category.
    Magento ver. 1.4.0.1

  19. kr says:

    Magento 1.4.2.0 has similar problem, displays all products not featured.

  20. GJ says:

    I’m using Magento 1.4.2.0 as well, I’d like to know if there is any updates on the script for my version.

    thanks!

  21. Teodor says:

    I am using 1.5.0.1 and it works OK! Many thanks for this great post.

  22. Rick says:

    getting error when try to load?

    Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in /app/code/local/Mage/Catalog/Block/Product/List/Random.php on line 4

    any ideas?

  23. Rick says:

    solved syntax error. for some reason when i cut and pasted some weird hidden char were added. cleaned it up with textwrangler and now all good. i cut and paste all day and never have run into this. hmm…

  24. Martin says:

    thx! this post helps a lot! Have searched for a solution so long.

  25. Peter says:

    Hi there,

    Tried this and failed but dying to get this working!

    I’m running on 1.4.1.1, I created the random.php (including php closing tag), uploaded to the new directory path in local, included the line in cms (see below) calling the correct block and correct template (custom list without toolbar) with the correct cat ids.

    {{block type="catalog/product_list_random" category_id="465" template="catalog/product/list_home.phtml" column_count="4" num_products="4"}}

    Problem is that it’s still calling from the whole catalogue and not the specified cat ids.

    I have 2 of these blocks on the home page using the same template in case that could create the problem? I did try and remove on of them but still the same result.

    Would be so incredibly greatful for help on this

    All the best

    Peter

  26. This line does all the trick for me to get the random product collection

    $collection->getSelect()->order(‘rand()’);

    Thanks :-)

  27. Tomas says:

    I have same problem as Peter, it callling all products from catalog, not from that category which is specified by id.
    I am using 1.6 version

    And Jerome, I have seen you comment in more blog’s but anythere you won’t clarifying how to do that.

  28. Tomas says:


    Tomas:

    I have same problem as Peter, it callling all products from catalog, not from that category which is specified by id.
    I am using 1.6 version
    And Jerome, I have seen you comment in more blog’s but anythere you won’t clarifying how to do that.

    And one more question what do you mean by telling that “create hidden category”, it can be active or not?

    I can see that comments here is quite old, but anywhere on web aren’t any good solutions, maybe if someone from blog owners would find a solution to this magento problem whole blog become much more popular? I am ready to make a donation for that :)

    And if not here is a link for extensions which I think would help to achieve needed goals: http://www.magentocommerce.com/magento-connect/product-randomizer-9307.html

  29. admin says:

    @thomas, I will ask one of the support team to take a look at this for 1.6

  30. Tomas says:

    It would be nice from your side :)

  31. Tomas says:

    Hi,

    any updates?

  32. Tomas says:

    Hi,

    how about ramdomize script? Do you have any news from your support team?

  33. Nik says:

    Thanks for this great code snippet and tutorial!
    However, I have one problem using 1.5.1.0 implementing this in a custom module…
    If I use this code, I can’t get Magento to generate the AddToCart URL for the products of this collection. It does work throughout the store for all other list views though, so it’s not a store issue I guess…

    Using this code:

    $collection = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('entity_id', array('in' => $productIds))
    ->addAttributeToSelect('*')
    ->addFinalPrice();
    Mage::getModel('catalog/layer')->prepareProductCollection($collection);
    $collection->getSelect()->order( "FIELD (`e`.`entity_id`,'".implode("','",$productIds)."')" );
    $collection->addStoreFilter();
    $this->products = $collection;

    return $this->products;

  34. Sam says:

    Thank you for the code man!

    I have just modified the same code and used in a .phtml file, named list_home.phtml

    We need to write code for home cms like:
    {{block type=”catalog/product_list” category_id=”50″ template=”catalog/product/list_home.phtml”}}

    Code:

    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;
    ?>
    count()): ?>

    __('There are no products matching the selection. Please provide a category ID.') ?>

    count() ?>

    <a href="getProductUrl() ?>" title="htmlEscape($_product->getName()) ?>">
    <img src="helper('catalog/image')->init($_product, 'small_image')->resize(105, 105); ?>" width="105" height="105" alt="htmlEscape($_product->getName()) ?>" />

  35. Akila says:

    A good methode.But here is a more flexible methode to add featured product randomly one by one.

    Try this one:
    http://www.awebsolution.info/magento-add-random-featured-products-home-page

    Thnak you

  36. kamaradski says:

    Great piece of code, thanks for this !!!

    One remark though, it seems to ignore the categori_id=”". Even when blank, or a non-existing ID, it always shows all products from all categories… Just like many comments above already mentioned.

    I’m runnin 1.7 RC2, is there any fox for this? even if it’s a dirty-hack directly in Random.php ?

    KR
    Kamaradski

  37. mau says:

    Thanks so much for your code, it works fine on my site. My store is configured to show also out of stock products, is there any way to edit this Random.php so magento won’t show out of stock products ONLY in the random category? Thanks again!

Leave a Reply