Filter product collection by multiple categories in Magento

During the past week I’ve dealed with a very weird and stressing thing with my colleagues: filtering a product collection by multiple categories in Magento.

  • Filter by only 1 category

Magento offers a type of filter that can be used directly from the collection:

$_category = Mage::getModel('catalog/category')->load($category_id);

$collection->addCategoryFilter($_category);
  • Filter by 2 or more categories

This is a completely different story. It’s very important to proceed correctly in order to avoid errors of the type:
[blockquote]Item (Mage_Catalog_Model_Product) with the same id already exist[/blockquote]

Proceed in the following way:

1. Call your collection and filter by the attributes you want to filter (all but the category one). For example:

$collection= Mage::getResourceModel('catalog/product_collection')
           ->addFieldToFilter('is_saleable',1)
           ->addFieldToFilter('type_id', array('eq' => 'configurable'));

2. After doing this, you can apply your multiple category filter as follows:

$categories_to_filter = array('3', '4', '5');
$ctf = array();

foreach ($categories_to_filter as $k => $cat) {
     $ctf[]['finset'] = $cat;
}

$collection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
            ->addAttributeToFilter('category_id',array($ctf));

Important: do it in this order if you don’t want to face weird Magento issues.

5 thoughts on “Filter product collection by multiple categories in Magento

  1. This filters multiple categories using an OR condition – is there any way to do this with an AND condition to get products which are in both category X and category Y?

  2. Hello,

    I nub in magento developpement, and when I read your post I have just one question :
    Where (in which file) do you put your code? ( In nmy case, I want this filter on left side in “Shop By” or “Browse By” block) ?

    Thanks for your answer

    • Hi Julien,

      I created a php script with this code that I put on my shell folder. After that, I executed the script using the terminal: php script.php.

      You will need to find some information on how to create Magento Shell Scripts.

  3. Pingback: Filter magento product collection by multiple categories | Nick Bartlett

Leave a Reply