cancel
Showing results for 
Search instead for 
Did you mean: 

Listing Random Products from all Children Categories

Listing Random Products from all Children Categories

Hi there, I need some help. I have the following category structure

 

category>subcagtegory>subsubcategory

 

The parent is an empty non-anchor category that serves as a landing page. I need to display a list of random products from all the subcategories and subsubcategories on the parent landing category. Right now I have the following Random.php

 

class Mage_Catalog_Block_Product_List_Random extends Mage_Catalog_Block_Product_List
{
    protected function _getProductCollection()
    {
        if (is_null($this->_productCollection)) {
            $categoryID = $this->getCategoryId();
            if($categoryID)
            {
              $category = new Mage_Catalog_Model_Category();
              $category->load($categoryID);
              $collection = $category->getProductCollection();
            } else
            {
              $collection = Mage::getResourceModel('catalog/product_collection');
            }
            Mage::getModel('catalog/layer')->prepareProductCollection($collection);
            $collection->getSelect()->order('rand()');
            $collection->addStoreFilter();
            $numProducts = $this->getNumProducts() ? $this->getNumProducts() : 3;
            $collection->setPage(1, $numProducts)->load();

            $this->_productCollection = $collection;
        }
        return $this->_productCollection;
    }
}

and I call it on the parent's category "Custom Layout Update" like this:

 

<reference name="content">
     <block type="catalog/product_list_random" name="product.list.random" template="catalog/product/random.phtml">
        <action method="setColumnCount"><count>5</count></action>
        <action method="setNumProducts"><num_products>20</num_products></action>
    </block>
</reference>

Everything works great but the random products are being pulled from the entire Magento catalog. Whereas, I need them to be pulled only from all the children categories of the current category. 

 

Thanks a lot in advance!

1 REPLY

Re: Listing Random Products from all Children Categories

@dbabaev

 

 

First check the category IDs are coming properly into the code or not?

If not then you can combine category wise filter into the code and filterable result returns from this collection, and you can get your desired output.

Found something useful, please give "Kudos" or "Accept as Solution" for Token of Appreciation.
Free Magento Extensions : https://magecomp.com/free-magento-extensions.html