Monday , December 11 2017
Home >> All tutorial >> Filter product collection by multiple categories in Magento

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:

  1. $_category = Mage::getModel(‘catalog/category’)->load($category_id);
  2.  
  3. $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:

  1. $collection= Mage::getResourceModel(‘catalog/product_collection’)
  2.            ->addFieldToFilter(‘is_saleable’,1)
  3.            ->addFieldToFilter(‘type_id’, array(‘eq’ => ‘configurable’));
2. After doing this, you can apply your multiple category filter as follows:
  1. $categories_to_filter = array(‘3’, ‘4’, ‘5’);
  2. $ctf = array();
  3.  
  4. foreach ($categories_to_filter as $k => $cat) {
  5.      $ctf[][‘finset’] = $cat;
  6. }
  7.  
  8. $collection->joinField(‘category_id’, ‘catalog/category_product’, ‘category_id’, ‘product_id = entity_id’, null, ‘left’)
  9.             ->addAttributeToFilter(‘category_id’,array($ctf));
Important: do it in this order if you don’t want to face weird Magento issues.

We also contribute great content of Magento Download for FREE (all versions)

DON'T MISS THE CHANCE!

magento download

About Champ

Leave a Reply

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

Heap | Mobile and Web Analytics