Home >How to Filtering a Magento Product Collection by Multiple Categories

How to Filtering a Magento Product Collection by Multiple Categories

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()
 ->addAttributeToFilter('status', 1)
 ->addAttributeToFilter('visibility', 4)
  • 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:

->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')
        ->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





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

< Previous Post
Next Post >
+ posts