Tutorialsplane

Magento get product collection filter by category


Magento get product collection filter by category : You can load products by the root category. First of all you need to get the root category id and then join product collection with the category product to get the products in that category. We have explained this with the following example


Magento get product collection filter by category

Below example shows the product list from root catgory-

$rootCatId = Mage::app()->getStore()->getRootCategoryId();

$collection = Mage::getResourceModel('catalog/product_collection')
->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left')
->addAttributeToFilter('category_id', array('in' => $rootCatId))
->addAttributeToSelect('*')
->load();

foreach($collection as $product){ 
    echo $product->getName()."<br/>"; 
    echo $product->getId()."<br/>"; 
};

Magento get product collection filter by Multiple category

If you want to load multiple categories products Use the below collection join and filter to get product list-

$collection = Mage::getResourceModel('catalog/product_collection')
->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left')
->addAttributeToFilter('category_id', array('in' => array(1,5,9)))
->addAttributeToSelect('*')
->load();

foreach($collection as $product){ 
    echo $product->getName()."<br/>"; 
    echo $product->getId()."<br/>"; 
};

Where 1,5 and 9 is category id. The above example will get the products from the above categories.