Magento – Random products in product widget

magento-1.7product-listrandom

I currently have 4 widgets on my front page that display 4 products each.

At the moment it uses either featured products, special producs or hot products to decide which products to populate the widget with.

I select the product types using the categories.

I'm looking for a way to randomize the products from the specific category.

Best Answer

The are two obvious approaches to achieve this. You can do it either within your theme or create a module that will utilise this functionality.

Within the theme you can just create a template (let's say in catalog/product/randomize.phtml) and put the following code in there:

$_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$productVisibility = Mage::getSingleton('catalog/product_visibility');
$_productCollection = Mage::getResourceModel('reports/product_collection')
                   ->addAttributeToSelect('*')
                   ->addStoreFilter()
                   ->addCategoryFilter($_category)
                   ->setVisibility($productVisibility->getVisibleInCatalogIds());
$_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));                  
$_productCollection->setPage(1, 4);

and then in your CMS page you put something like this:

{{block type="core/template" name="whatever" template="catalog/product/randomize.phtml" category_id="YOUR_CATEGORY_ID"}}

The second approach is to create your module with just one block, extend Mage_Catalog_Block_Product_List and then implement _getProductCollection method in almost the same manner as in first approach:

protected function _getProductCollection()
{
    if (is_null($this->_productCollection)) {
        $_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
        $productVisibility = Mage::getSingleton('catalog/product_visibility');
        $this->_productCollection = Mage::getResourceModel('reports/product_collection');
        $this->_productCollection->addAttributeToSelect('*')
            ->addStoreFilter()
            ->addCategoryFilter($_category)
            ->setVisibility($productVisibility->getVisibleInCatalogIds());
        $this->_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));                  
        $this->_productCollection->setPage(1, 4);
    }

    return parent::_getProductCollection();
}

Then in your CMS page you can call your block like this:

{{block type="module_name/block_name" name="whatever" template="catalog/product/list.phtml" category_id="YOUR_CATEGORY_ID"}}
Related Topic