Magento – Filter product collection by multiple categories

Magento providing verious type of filter that can be used directly from product collection. Including category filter,

$_category = Mage::getModel('catalog/category')->load($category_id);
$collection= Mage::getResourceModel('catalog/product')->getCollection()->addCategoryFilter($_category);

But the issue is with multiple categories to filter. You can use bellow code to overcome this problem,

$collection = Mage::getModel('catalog/product')->getCollection()
             ->addAttributeToSelect('*')
             ->addFieldToFilter('is_saleable',1)
             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
             ->addAttributeToFilter('category_id', array(
                 array('finset' => '4'),
                 array('finset' => '8'))
               )
             ->addAttributeToSort('created_at', 'desc');
Advertisements

4 thoughts on “Magento – Filter product collection by multiple categories

  1. Pingback: Magento – Filter product collection by multiple categories | Kenneth Carnesi

  2. i got error when i use above code like this:-
    $this->_collection->addFilter(‘store_id’, array(
    array(‘finset’ => ‘1’),
    array(‘finset’ => ‘0’))
    );
    in my custom extension please guide me.
    thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s