How to get random products if I have no related products in magento

I have a problem. I want to show 4 related products on the product page. It's simple and I did it. But if a product has no or less than 4 products, I want the remaining product to appear randomly on the page.

+3


source to share


2 answers


To select 4 random products, first you need to rewrite the class responsible for the corresponding block (or just move that file to a local folder) and change the logic for the function that returns the collection to something like the following code:

$productsCollection = Mage::getResourceModel('catalog/product_collection');
$productsCollection->getSelect()->order('rand()');
$productsCollection->getSelect()->limit(4);

      



Hope this is helpful

+2


source


If you're only interested in building this functionality on the product page, you can find most of the magic in Mage_Catalog_Block_Product_List_Related::_prepareData()

.

In order to fill your related products with random products, we first need to know exactly how many random products we need. In this case it is (4 products found):

// Existing Magento code near end of method
$this->_itemCollection->load(); 

// Our code
$numRandomsToGet = 4 - count($this->_itemCollection);

      



Then we can get the corresponding number of random products and add them to the collection:

// Our code
$randCollection = Mage::getResourceModel('catalog/product_collection');
Mage::getModel('catalog/layer')->prepareProductCollection($randCollection);
$randCollection->getSelect()->order('rand()');
$randCollection->addStoreFilter();
$randCollection->setPage(1, $numRandomsToGet);
$randCollection->addIdFilter($this->_itemCollection->getAllIds(), true);

foreach($randCollection as $randProduct)
{
    $this->_itemCollection->addItem($randProduct);
}

// Existing Magento code
foreach ($this->_itemCollection as $product) {
    $product->setDoNotUseCategoryId(true);
}

return $this;

      

Caveat / Plug: I pulled this code from our add- ons extension for Magento , so there might be something external to this method to do, but I don't think so. If you get stuck, you can try downloading the extension and explore the code completely. Or, of course, you can just use the as-is extension.

+1


source







All Articles