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.

    • Greg on May 25, 2013 at 8:02 am

    Reply

    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?

  1. Reply

    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

      • Pau on September 29, 2013 at 7:04 am
      • Author

      Reply

      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.

  2. Reply

    Thanks for sharing this. I too struggled with this a few weeks ago. Kinda a thorn in my side trying to figure it out 🙂

    • Nasir Perwaiz on August 18, 2014 at 11:00 am

    Reply

    Hi,

    Using the above code gives me the following error,

    Joined field with this alias is already declared

    Any idea how to solve it.

    Thanks.

    Nasir Perwaiz

  3. Reply

    Thanks a lot! Its really helpfull. I have tried to lot to do the same but nothing was working and finally it helped me. 🙂

Leave a Reply

Your email address will not be published.