Question

I have been working on my own theme from the default RWD on 1.9.2.1.

I would like to limit the related products to show only 8 products instead of all of the say 139 I have currently for a single product.

Also, I would like to randomise so pick at random 8 from all of the related products.

I am aware that I could simply add a break in the loop so when it has iterated 8 times it'll stop, but this I believe can be waste of resources.

I have gathered that the code below is responsible for creating the collection of related products. So, how would I amend this in the correct way to limit to 8 products and choose at random?

    $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->load();

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

        return $this;
Was it helpful?

Solution

In hindsight this was quite an easy question to solve: By adding the two lines below in the _prepareData() function above the itemCollection load.

However, although I am still new to the magento world I know you should never edit core files and instead should extend the module that you want to change. But, sadly this is above my knowledge so if someone could incorporate my answer so it is deemable as being done the correct way then I'd appreciate it.

$this->_itemCollection->getSelect()->order('rand()');
$this->_itemCollection->setPage(1, 8);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top