cancel
Showing results for 
Search instead for 
Did you mean: 

Randomise and limit the related products list

Randomise and limit the related products list

I am currently making my own theme for a site in magento 1.9.2.4 and would like to limit the number of related products shown for a given product to a random 5.

 

in app -> code ->core->mage->core->block->product->list->related.php:

 

    protected function _prepareData()
    {
        $product = Mage::registry('product');
        /* @var $product Mage_Catalog_Model_Product */

        $this->_itemCollection = $product->getRelatedProductCollection()
            ->addAttributeToSelect('required_options')
            ->setPositionOrder()
            ->addStoreFilter()
        ;

        if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
            Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
                Mage::getSingleton('checkout/session')->getQuoteId()
            );
            $this->_addProductAttributesAndPrices($this->_itemCollection);
        }
//        Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_itemCollection);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);

$this->_itemCollection->getSelect()->order('rand()');
$this->_itemCollection->setPage(1, 5);

        $this->_itemCollection->load();

        foreach ($this->_itemCollection as $product) {
            $product->setDoNotUseCategoryId(true);
        }

        return $this;
    }

I simply edited this function to have the two lines above the item collection load:

 

$this->_itemCollection->getSelect()->order('rand()');
$this->_itemCollection->setPage(1, 5);

This successfully does what I am after, but one editing core files is a big no, and order('rand()'); is very resource draining and negative impact on performance, due to it's need to create a tmp table. 

 

So, what I was wondering is if anyone could help me to create a solution that does not require core files edit and a more performance efficient solution.

1 REPLY 1

Re: Randomise and limit the related products list

It works! For the moment what I did is put it under local in the mean time.