Magento 1 Product Filtering – How to Filter Product Collection by Multiple Categories

categorycollection;filtermagento-1

I have this snippet of code that gets the most recently added products:

$_productCollection = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('*')
                ->addAttributeToFilter($preorderAttribute, array(
                    'eq' => Mage::getResourceModel('catalog/product')
                        ->getAttribute($preorderAttribute)
                        ->getSource()
                        ->getOptionId($preorderValue)
                ))
                ->setVisibility(array(2,3,4))
                ->setOrder('created_at', 'desc')
                ->setPage(1, 12);

I want to further filter this by category, for example, categories with id 3 and 4. Only products from 3 and 4 categories are selected in the collection. How can I achieve this?

I tried to use addAttributeToFilter to filter by category IDs but there seems to be a variety of different ways to do it, and it's neither not working or simply gives a Fatal error:

Call to a non-member function getBackend()

….now I'm at a loss.

Any help would be appreciated.

Best Answer

The following code example works for me to show only particular two categories (7 and 8) products. Hope it will work for you:

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

foreach($productCollection as $product){
    echo $product->getId() . "<br/>\n";
};
Related Topic