How to Display only 3 related product on product view page, Magento?
Asked Answered
M

3

7

I am displaying related products in content block of layout in product view page. My code in catalog.xml is:

<reference name="content">
     <block type="catalog/product_list_related" name="catalog.product.related" after="-" template="catalog/product/list/related.phtml"/>
</reference>

Now, all the related products are displayed in my product view page, but I want to display only 3 products, What should I do? Please, anybody can help ??

Marotta answered 10/5, 2013 at 12:40 Comment(0)
H
10

You need to edit the template file catalog/product/list/related.phtml and limit the loop to only iterate through 3 products.

For example:

    ...
    <?php $i = 0; ?>
    <?php foreach($this->getItems() as $_item): ?>
        <?php if($i++ == 3) break; ?>
        ...
Hell answered 10/5, 2013 at 13:4 Comment(2)
thnx @zitix, it worked for me. Though its static, but worked for now. :)Marotta
here you will be getting a bigger collection while you want only three. so this will be more resource intensive.In your collection code add this limit of 3.Transpose
J
5

This worked for me. You have to limit the query, and maybe shuffle it before loading the collection. Open the file \app\code\core\Mage\Catalog\Block\Product\List\Related.php and look for the method:

Mage_Catalog_Block_Product_List_Related->_prepareData()

Add this line before the load() call.

$this->_itemCollection->getSelect()->limit(3)->order(new Zend_Db_Expr('RAND()'));

It is still not pretty, !!you should not write in the core code!!, but it's a good start.

Jinni answered 17/11, 2014 at 23:14 Comment(3)
This is the perfect answer. Just to add, one should rewrite the classLedoux
this is wrong method because you overwrite core files. You must write model to extend this class if you need change code logic.Side
@Side Translation: "It's the wrong method because it's not the one I want". Go away!Antisthenes
N
1

You have a collection of products prepared in Mage_Catalog_Block_Product_List_Related and it is iterated in the template file catalog/product/list/related.phtml. If you have any rule that should add to limit your collection, you can override the _prepareData() method and modify the collection. If not, the easiest solution is to exit from the loop in the phtml after three iterations.

Nebulize answered 10/5, 2013 at 13:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.