The article is written for a purpose of filtering a lot of products which belong to many different categories.
I have tried a lot of scripts, but all of them did not work as effectively as this code below. The script is extremely effective.
- First of all, we need to build a product collection and then filter as the normal way; however, we just need to select ids:
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('id')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->addStoreFilter();
- Next, we need to create a simple array of category id:
$catfilters = array(10, 20, 25); //Obviously your category ids will be different
$conditions = array();
foreach ($catfilters as $categoryId) {
if (is_numeric($categoryId)) {
$conditions[] = "{{table}}.category_id = $categoryId";
}
}
- Then, we join with category table by using this code below in order to select ids collection of products filtered and join with the category table:
$collection->distinct(true)
->joinField('category_id', 'catalog/category_product', null,'product_id = entity_id', implode(" OR ", $conditions), 'inner');
$idProducts = $collection->getAllIds();
- Now, we have a product collection filtered by categories and attributes of products:
$collection = Mage::getResourceModel('catalog/product_collection')
->setStoreId($this->getStoreId())
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array('in' => $idProducts) )
;
In this solution, we use:
– distinct(true), a function of collection, in order to return different values
– {{table}} in a combined code to join in a table in the JoinField function so as to name the joined table
– join inner: to get data from 2 different tables
Reference:
If you get any trouble when trying to filter by this code, you can contact us via our email:
support@bsscommerce.com or Skype: support.bsscommerce
Hi,
Can you please tell me where we need to add this code.
Thanks,
Rajmohan
Dear,
You can add this code after you’ve create category collection in a block. $collection variable can be create using the code in tutorial.
ex: $collection = Mage::getModel(‘catalog/product’)->getCollection()
->addAttributeToSelect(‘id’)
->addAttributeToFilter(‘status’, 1)
->addAttributeToFilter(‘visibility’, 4)
->addStoreFilter();