Filter magento product collection by multiple categories


I spent quite a bit of time on this today and wanted to share the solution as it was not easily found on Google. I have a product collection and want to filter it by multiple categories… pretty much all sub categories of a given parent category. I tried using built in magento functions like addAttribteToFilter and addFieldToFilter and they both result in a “Call to a member function getBackend() on a non-object” error.

I finally found a solution on this site http://www.catgento.com/filter-product-collection-by-multiple-categories-in-magento/ . An example of my final code is below

parentCategoryId = 9;
$childCategories = Mage::getModel('catalog/category')->getCategories($parentCategoryId);
foreach($childCategories as $category) {
	$categoryIds[] = $category->getId();
}
 
//get newest used tanning bed product
$collection = Mage::getModel('catalog/product')->getCollection();
foreach ($categoryIds as $k => $cat) {
	$filter[]['finset'] = $cat;
}
$collection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
	->addAttributeToFilter('category_id',array($filter));

Leave a comment

Your email address will not be published. Required fields are marked *