Thursday, August 19, 2010

Magento – Filter by multiple categories

create local copy of this modal:
app\code\local\Mage\Catalog\Model\Resource\Eav\Mysql4\Product
edit collection.php add this function:-

public function addCategoriesFilter(array $categories)
{
// print_r($categories);
//echo $this->getStoreId() ;
$this->_prepareProductLimitationFilters();
$this->_productLimitationJoinWebsite();
$this->_productLimitationJoinPrice();
$filters = $this->_productLimitationFilters;

$conditions = array(
'cat_index.product_id=e.entity_id',
$this->getConnection()->quoteInto('cat_index.store_id=?', $this->getStoreId())
);
if (isset($filters['visibility']) && !isset($filters['store_table'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.visibility IN(?)', $filters['visibility']);
}
$conditions[] = $this->getConnection()
->quoteInto('cat_index.category_id IN(?)',$categories);
if (isset($filters['category_is_anchor'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.is_parent=?', $filters['category_is_anchor']);
}

$joinCond = join(' AND ', $conditions);
$this->getSelect()->join(
array('cat_index' => $this->getTable('catalog/category_product_index')),
$joinCond,
array('cat_index_position' => 'position')
);


$this->_productLimitationJoinStore();

Mage::dispatchEvent('catalog_product_collection_apply_limitations_after', array(
'collection' => $this
));

return $this;
}




At your module block use this function to get products collection from multiple categories :-

public function _getProductCollection(){
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
);
$categories=array(3,4,5,6,7,8);
$storeId = Mage::app()->getStore()->getId();
$this->_collection = Mage::getModel('catalog/resource_eav_mysql4_product_collection')
->setStoreId($storeId)
->addCategoriesFilter($categories)
->addAttributeToFilter('visibility', $visibility)
->addAttributeToSelect('*')
->setOrder('created_at', 'desc')
->addAttributeToSelect('*');
return $this->_collection;

}

2 comments:

  1. Hi,

    Where is the module block located?

    ReplyDelete
    Replies
    1. Hi Erin,
      apologies for such a really late reply (more then 1 yr phew!) but in case you still couldnt find where the block is located its most likely located at app/code/local/custom_module_interface/custom_module/block/
      hope this helps

      Delete