0

I'd like to display 4 random products from a specific category on the right hand side of my product page. The effect I'd like to achieve is exactly like the Related Products and Compare Products block that appear under those conditions.

So far I've taken the code from related.phtml and placed it in another file and updated my templates layout.xml.

However looking at the code, I cannot see where I would call a category or specify how many products to display.

How can I use the related.phtml file as a template to display 4 random products from a specific category in the right block?

2

you can use the related.phtml template as long as the block behind it passes a collection as expected. Create a custom extension with a block class something like this below

class [Namespace]_[Module]_Block_Related extends Mage_Catalog_Block_Product_List_Related
{

    protected function _prepareData()
    {
        [...]

        $this->_itemCollection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('thumbnail')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('...') // whatever you need
            ->addCategoryFilter($category) // category is an instance of Mage_Catalog_Model_Category
            ->setPageSize(4);

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

        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_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);

        $this->_itemCollection->load();

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

        return $this;
    }
}

and use that to display the items from your local.xml

<reference name="right">
   <block type="[module]/related name="category_related" template="catalog/product/list/related.phtml"/>
</reference>
  • I guess there's no way to do this without creating a module? :) – SR_Magento Mar 27 '14 at 14:18
  • You can add the PHP code to a view file but I highly recomment against it – Sander Mangel Mar 27 '14 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.