How to display bestselling products in Magento + source code

How to display bestselling products in Magento

We’ve noticed that many store owners ask questions about methods of displaying bestselling products on their Magento stores. Say, you need to show the most popular items on your Home page or Category View page.

Unfortunately, there’s no such default feature in Magento, but you can easily do this yourself. Read on to see the instructions!

Steps to display bestselling products on a page in Magento

1. Create a new file for Block:

Magento_root/app/code/local/Mage/Catalog/Block/Product/Bestseller.php

You can download the file for free at the end of the article. The file contains the algorithm of returning the necessary products collection, Bestsellers in our case.

2. Create a template file for the new block:

Magento_root/app/design/frontend/base/default/template/catalog/product/bestseller.phtml

You can download the file for free at the end of the article. This file works with visualization of our bestsellers collection on a given page. It is just an example; you are welcome to use the list.phtml template from your theme. Please do not forget to do that so the look of the collection is adjusted to your website’s design.

3. Now you need to call the created block, to do that go to Backend > CMS > Pages > Edit Page ‘Home page’ and add the following lines of code:

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml" header="Bestsellers" limit=4}}

Also you can add a new block via layout update:

<reference name="content">
        <block type="catalog/product_bestseller" name="bestseller" template="catalog/product/bestseller.phtml" before="-">
            <action method="setLimit"><limit>3</limit></action>
            <action method="setHeader"><header>Best Sellers</header></action>
        </block>
</reference>

For instance, try to add this block to the Category View page here:

Backend > Catalog > Manage Categories > Click needed category in the category tree > `Custom Design` horizontal tab > ` Custom Layout Update` field

Feel free to manipulate the result using the header and the limit variables.

If just adding a list of bestsellers is not enough, consider checking the Improved Sorting extension, which is also compatible with layered navigation. It lets your customers sort the products by Best Selling, Most Viewed, Top Rated, Reviews Count, and other parameters.
Please note that this solution doesn’t work with Flat Catalog. To make this work, please disable this option in your store settings.

SUPEE-6788 update

When adding the block to the CMS page or Static block and using the following code:

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml" header="Bestsellers" limit=4}}

you need to create a permission for this block:
Backend – > System – > Permissions – > Blocks – > `Add New Block` button
Bestseller SUPEE-6788 update
This manipulation is needed to be done for Magento 1.9.2.2 and higher or after installing SUPEE-6788 security patch.
Adding the block via Custom Layout Update works well in any situation:

<reference name="content">
<block type="catalog/product_bestseller" name="bestseller" template="catalog/product/bestseller.phtml" before="-">
<action method="setLimit"><limit>4</limit></action>
<action method="setHeader"><header>Best Sellers</header></action>
</block>
</reference>

26.01.2016 update

The code now works with flat catalog, plus the category variable is added, and you can use a certain category for the product selection.
Add Magento bestsellers via CMS block:

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml" header="Bestsellers" limit=4 category=24}}

Add Magento bestsellers via layout update:

<reference name="content">
    <block type="catalog/product_bestseller" name="bestseller" template="catalog/product/bestseller.phtml" before="-">
        <action method="setLimit"><limit>4</limit></action>
        <action method="setHeader"><header>Best Sellers</header></action>
        <action method="setCategory"><category>24</category></action>
    </block>
</reference>

Download the Bestseller.php and the bestseller.phtml files with source code for free:

Ksenia Dobreva

Ksenia Dobreva

Ksenia is a devoted marketer with special love to blogging. She believes that content with several pinches of SEO and social can be a brilliant daily special. When she’s not working on Amasty updates and blog posts, Ksenia runs a blog on movies and books and helps animal shelters.

You may also like...

73 Responses

  1. Ashish @ MagikCommerce says:

    We typically build this feature set in our themes only but separating the code out like you did for others is great. Especially for those theme which doesn’t come powered with this functionality out of the box.

  2. andrew says:

    Thanks for sharing the script!

  3. Cosimail says:

    Hi, thank you for your post, which is great and works pretty well.
    I have a question: how can I choose how many products per row to display?
    I tried 5 but it does not works…
    Thank you very much

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi and thanks for reading! Try adding limit=”3″ where 3 is the quantity of products.
      ‘limit’ variable enables you to specify the number of products in the block.
      Please let me know if that helps.

  4. Cosimail says:

    Sorry, but there was an error in the comment: I wrote a string of code, but then appears only the number “5” instead of the code, I don’t know why… My real question is: what code I must put to specify the number of products per row to display? I want to display 3 rows of 5 items: total 15 items. Thank you in advance

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi and sorry for the late answer!

      I just wanted to point out that this guide is an example of a solution. It shows data in 1 row using limit parameter, which contains the number of products for the selection.

      If you need to show more than 1 row (3 rows 5 products each), you need to edit your template bestseller.phtml, and pass limit=15.

      Hope that helps!

  5. Cosimail says:

    Hi, thank you for your kind answer!
    What means “pass limit=15”? This is what I get now: mycakesdecorating.com/best-seller-ever

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi again! From what I can see here, your script shows bestselling 15 items but you still need to customize the template so it shows the items in three rows, not one.

  6. Cosimail says:

    Thank you!!! :)

  7. Alldo says:

    When we add this code, there’s no best selling products showing up? Where does Magento store this information? Do we need to enable something, maybe running an report refresh or similar?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi and thanks for the question!
      Did you clear the cache (both in the browser and in Magento)? If not, please try that.
      Technically, bestsellers aren’t stored anywhere in the database separately. The php code analyses the database and pulls the bestsellers, and the template shows them.

      • Alldo says:

        Thanks Ksenia, and yeah, that’s it, it’s running now, sort of. I’m afraid there still are some sort of problem? We are on Magento 1.9.1 and MySQL 5.6. We now got this report when running the script?

        cat ../var/report/467165546016

        a:5:{i:0;s:2267:”SELECT SUM(order_items.qty_ordered) AS ordered_qty

        “;i:1;s:6688:”#0 /usr/local/www/apache24/webroot/multistore/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)

        Any idea?
        Can’t find any error messages in the report 😛

        • Ksenia Dobreva Ksenia Dobreva says:

          Could you please provide us with the link you’re trying to place bestsellers on? Also, we’d love to have a look at the full report file (if it’s not convenient to place it here you’re welcome to send me the full report at ksenia.dobreva(at)amasty.com)

  8. alami says:

    thanks lot of Dobreva .

  9. Sundaramoorthy says:

    Hi i am new to magento in my site its not working,where i want to put this {{block type=”catalog/product_bestseller” template=”catalog/product/bestseller.phtml” header=”Bestsellers” limit=4}} in home page and also this

    3
    Best Sellers

  10. Sandeep says:

    Can you let me know how to display the Category Products on a single row with Slider and no list grid tool bar
    Also I get the grey background if I try to display anything on homepage.

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Sandeep!
      Thanks for stopping by.
      It’s difficult to give answers when we can’t see what exactly you are doing.
      In general, all the settings for catalog display can be found at System > Configuration > Catalog > Catalog. Home Page is changed at CMS > Pages > Home Page.
      If you need something that’s not in the settings and there is no such extension, you’ll probably need a customization made by a developer.
      Hope that helps.

  11. Mikael says:

    Thanks for nice guide, but this does not work if you have enabled flat catalog. You should put that into guide :)

    • Ksenia Dobreva Ksenia Dobreva says:

      Oops!
      Thanks so much for pointing this out. Indeed, there’s an issue with flat catalog, we will definitely correct this and update the downloadable code very soon.

      • Erwin says:

        Hi Ksenia, very useful piece of code but can you update me if the code is updated to work with flat catalog on Magento 1.9.x? If not is this on your planning? Thank you in advance, Erwin.

        • Ksenia Dobreva Ksenia Dobreva says:

          Hi Erwin, thanks for your interest. For now the code is not adapted to work with flat catalog, we will definitely consider the fact that even more people need this feature. Unfortunately, I can’t promise any exact date here =)

  12. David - objectsource says:

    This is great – very useful for out latest project. Look clean and follows good practice as well.

  13. zaw says:

    “Magento_root/app/code/local/Mage/Catalog/Block/Product/Bestseller.php” this path do we have to create ourselves or was it already exist? because there is no local folder under magento_root/app/code

    where exactly is this layout update xml should we place in? “Also you can add a new block via layout update:” sorry i’m still very new to magento.. was just trying to add this to my home page Thanks!

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey!

      Thanks for your questions.

      “Magento_root/app/code/local/Mage/Catalog/Block/Product/Bestseller.php” this path do we have to create ourselves or was it already exist? because there is no local folder under magento_root/app/code”

      Yes, indeed, the local directory isn’t included into Magento 1.9.1.0 installation by default, but this doesn’t mean you can’t use it, you can, don’t hesitate to create it.
      For more information:
      http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/how_to_create_a_local_copy_of_app_code_core_mage#how_the_local_folder_works

      Now, to the second question.

      “where exactly is this layout update xml should we place in? Also you can add a new block via layout update:”

      Use the same path as in point 3 of the article:
      Backend > CMS > Pages > Edit Page ‘Home page’ 
      Also, here’s a screenshot for you as well.

      Hope that helps!

      • zaw says:

        Hi Hi, Thanks a lot for helping me on this! So now I did created the local folder with all empty folders inside and put the Bestseller.php file in there. Still doesn’t work.. actually it doesn’t really load the bestseller.phtml .. i think it should at least show some html DIV like this one “” even if the $this->getCollection(); was failed right?

        I tried both method to print out the block “{{block type=”catalog/product_bestseller” template=”catalog/product/bestseller.phtml” header=”Bestsellers” limit=4}}” in my home page content and layout update that you showed me.. both of them doesn’t seem to work.. I am not sure if its because of the block type “catalog/product_bestseller” was not recognized or link to our class file?

        • Ksenia Dobreva Ksenia Dobreva says:

          Hey!

          I’m sorry you faced some difficulties here. Thanks for providing the details!
          I’m afraid the developer needs to have a look at your installation to help you.

          Could you please shoot an email to support@amasty.com, please mark that the letter is about the free bestsellers script (so we could forward the ticket to the right developer) and give us your credentials. My colleague will have a look and help you.

          Cheers!

  14. john nusom says:

    I am looking to make the template for the bestseller products to be responsive.. is there sample .phtml you have that is responsive?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey!
      Unfortunately, we don’t have a responsive template available. But you can create your own using list.phtml template from your theme. Hope that helps.

  15. Purushartha says:

    Hi Ksenia,
    Did exactly as per your instruction and received the following “There has been an error processing your request SELECT SUM(order_items.qty_ordered) AS `ordered_qty`,………..). We are on CE 1.9. Will be great if you can lead me to the right direction.

    Thanks!

  16. pandiyan says:

    When we add this code, there’s no best selling products showing up? It only display best selling name. please help me

  17. pandiyan says:

    ya i got the mail.

  18. pandiyan says:

    Hi Ksenia,

    I am struggling with this concepts past four days, Please help me.

  19. pandiyan says:

    Hi Ksenia,

    Please check your email.

  20. pandiyan says:

    Hi Ksenia,

    I want to paste this script {{block type=”catalog/product_bestseller” template=”catalog/product/bestseller.phtml” header=”Bestsellers” limit=4}} or add any other specific category id inside of this script ?

  21. savita says:

    He,

    Please mail that code for increase limit of best selling products….

    savita@b2cmarketing.in

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey, you can edit the code yourself. {{block type=”catalog/product_bestseller” template=”catalog/product/bestseller.phtml” header=”Bestsellers” limit=4}} – limit is the parameter you need.

  22. Luca Ricci says:

    Hello Ksenia,

    thanks for sharing this.
    I tried your code but magento is throwing an “THERE HAS BEEN AN ERROR PROCESSING YOUR REQUEST” issue.
    From error log file i found the query and tried it directly from phpmyadmin and having this error:
    Unknown column ‘e.cost’ in ‘field list’
    I’m using Magento CE 1.9.0.1

    Best regards,
    Luca

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey Luca,

      thanks for asking.

      Unfortunately, it’s complicated to say what’s going on without seeing the code on the website.

      Feel free to send me (ksenia.dobreva@amasty.com) your FTP credentials, backend login and password and the link of the page you’re using the code on. I’ll ask my colleague to have a look.

  23. Joe says:

    Hey Ksenia,

    I have successfully added the bestseller script and it works nicely. I am however struggling with getting the star ratings for the products in the collection. Can you offer guidance on how to do this?

    Thank you

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey,

      thanks for asking.
      Please add the following line of code in the `bestseller.phtml` (somewhere in the foreach loop):

      < ?php echo $this->getReviewsSummaryHtml($p, true, true); ?>

  24. Abid Malik says:

    Thank you, the “SUPEE-6788 update” section solved my problem. and saved the day finally.

  25. xuannd says:

    Thanks for sharing.
    For now the code is not adapted to work with flat catalog, and I fixed this issuse.
    @Ksenia Dobreva, please update this guide.

    class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract {

    protected function _beforeToHtml(){
    // Get limit products
    $limitProducts = $this->getLimit();
    if($limitProducts == “”) $limitProducts = 12;

    $storeId = Mage::app()->getStore()->getId();
    $products = Mage::getResourceModel(‘reports/product_collection’)
    ->addAttributeToSelect(‘*’)
    ->addAttributeToSelect(array(‘name’, ‘price’, ‘small_image’))
    ->addOrderedQty()
    ->setStoreId($storeId)
    ->addStoreFilter($storeId)
    ->setOrder(‘ordered_qty’, ‘desc’); // Best sellers on top

    // Enabled flat catalog product
    if (Mage::helper(‘catalog/product_flat’)->isEnabled()) {
    $products->getSelect()->joinInner(array(‘e2’ => ‘catalog_product_flat_’.$storeId), ‘e2.entity_id = e.entity_id’);
    }

    Mage::getSingleton(‘catalog/product_status’)->addVisibleFilterToCollection($products);
    Mage::getSingleton(‘catalog/product_visibility’)->addVisibleInCatalogFilterToCollection($products);

    // Get best sellers for specific category
    if($categoryId = $this->getData(‘category_id’)){
    $category = Mage::getModel(‘catalog/category’)->load($categoryId);
    $products->addCategoryFilter($category);
    }

    // Set limit products
    $products->setPageSize($limitProducts)->setCurPage(1);

    $this->setProductCollection($products);

    return parent::_beforeToHtml();
    }
    }

  26. Kico Zaninetti says:

    Hi Ksenia, thanks for your code. I really don’t know what’s happening here. When I print_r() the collection it returns products, but the $products->getSize() is always 0 and the foreach($products as $p) don’t iterate.
    Any clues?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Kico, thanks for your question.
      I’m afraid it’s difficult to say what’s wrong without seeing the installation. If you want, you could send me your credentials at ksenia.dobreva@amasty.com (ftp and backend), and we’ll have a look. Cheers!

  27. Nilesh says:

    how to display most viewed product??

    • Ksenia Dobreva Ksenia Dobreva says:

      Hi Nilesh,

      To answer your question, we actually need to write a new article, as for the most viewed products you’ll need to take the data from another table, and therefore the code will be different.

  28. shailendra says:

    your code works fine for me thanks :)

  29. Anooj Mathew Varghese says:

    Hi Guys,

    Thank you for the code. This was working perfectly fine on my local host testing machine. However, when i uploaded the same to online one its not working. What could have gone wrong?

    Online version of Magento 1.9.2.4
    Local Host version of Magento 1.9.2.3

    Is the difference in version causing this issue. Can anyone help me out

  30. Anooj Mathew Varghese says:

    Hi Guys,

    I fixed the issue, Thank you for the code again working perfectly fine.

    If any of you guys are facing this issue. Go to system-> magento connect and reinstall only the mage core files.

  31. Vipul says:

    How to add pagination to this?

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey there and thanks for the question.

      Well, the article was more about creating a collection, and pagination is a different task, that’s why we didn’t describe it. You can use any jQuery slider for a fast result, and if you want to add real pagination, it’s a good idea to dig into this: Magento_root\app\code\core\Mage\Catalog\Block\Product\List\Toolbar.php

      Hope that helps!

  32. Magento_oCodewire says:

    Nice script but have one question that how to add this script and where Magento store this information.

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey there and thanks for asking.

      1) how to add this script
      Well, this process is described in the article. You create the necessary files and use one of the two ways of adding them (layout update or call CMS block)

      2) where Magento stores this information

      Depends on which information you’re talking about.

      2.1) sales info is taken from sales_flat_order_item database
      2.2) product info:
      а) if flat is included from the corresponding data base (depends on the store) – from catalog_product_flat_X (where X is the store id)
      b) if flat is not included, then the info is taken from EAV, I won’t list all the tables because there’s a lot of them.
      2.3) stock status info is taken from the corresponding tables.

      Hope that helps.

  33. Gags says:

    Hi Ksenia,
    Does this work with Magento 2.1 ?

  34. Stefan says:

    How can i implement this with my theme called ‘Ultimo’. I want the best sellers to show as i slider, check the page: frokungen . se . There you can see sliders on home page.

    • Ksenia Dobreva Ksenia Dobreva says:

      Hey Stefan, thanks for the question, but it looks like the answer would be a whole new article =) It’s quite difficult to answer your question in a single comment. Try modifying this template: Magento_root\app\design\frontend\base\default\template\amasty\amsorting\

Leave a Reply

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