Get Array of Product IDs for a Given Category in Magento

categorycollection;product-collectionsql

I am trying to find the fastest way of getting a list/array of product id's for any given category id.

I understand this is quite fast $category = new Varien_Object(array('id'=>$_cat));
$positions = Mage::getResourceModel('catalog/category')->getProductsPosition($category);

but there must be a way of getting the individual id's in 1 go.

So my question is: how can I retrieve an array of productids from a category id?

(Ad. where the is_anchor attribute is respected – for this Magento this means that also underlying category products are added to the collection)

also read; http://www.blog.plazathemes.com/archives/2759

Best Answer

If you only have the category ID and do not want to load the category itself, you can use this code (given category id $categoryId):

$category = Mage::getModel('catalog/category')->setId($categoryId);
$productCollection = Mage::getResourceModel('catalog/product_collection')
    ->addCategoryFilter($category)
    ->getAllIds();

This code respects the is_anchor attribute because the filter is using the index, so as a result it returns all products that Magento would show on front-end, including products from the underlying sub-categories.