Magento – Get all products of a category only – without products of its child categories

category-productscollection-filteringproduct-collection

I'm trying to get all products of a certain category. Unfortunately I always get not only all products of the category but also all products from its child categories. What am I doing wrong?

For example I'm working with following code snippet:

$catId = 160;
$category = Mage::getModel('catalog/category')->load($catId);
$collection = $category->getProductCollection()->addAttributeToSort('position');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);

foreach ($collection as $product) {
var_dump( $product->getId() );
}

Above category (ID 160) contains 17 products but I get 51 products. If I look these up I see that all these products are assigned to one of the child categories of category ID 160. Sometimes even a sub-sub-category of #160.

Ran a full reindex – didn't help. Caches are all disabled.
Magento ver. 1.9.2.0

Thank you so much in advance!

Best Answer

Figured it out myself.

$category_id = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
$category = Mage::getModel('catalog/category')->load($category_id);
$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addCategoryFilter($category)
    ->setOrder('price', 'ASC')
    ->load();

you can also use for more than one category as bellow:

$categoryIds = array(2,4);//category id

$collection = Mage::getModel('catalog/product')
                             ->getCollection()
                             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
                             ->addAttributeToSelect('*')
                             ->addAttributeToFilter('category_id', array('in' => $categoryIds))

I hope this will help you.