6

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

5

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.

  • @ShirtsofHolland thanks for the edit suggestion, I extended it with more information – Fabian Schmengler Aug 14 '15 at 7:13
  • thanks. However $category = Mage::getModel('catalog/category')->setId($categoryId)->setIsAnchor(false); $includeIDs = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($category)->getAllIds(); doesnt show the collection without underlying products. We tried this many times - but it just doesnt give the expected result .... – ShirtsofHolland Aug 14 '15 at 7:14
  • OK I made a wrong assumption here. The anchor attribute is already respected in the category_product index and the index is used by this collection filter. I fixed the answer. – Fabian Schmengler Aug 14 '15 at 7:28
4

Try this:

$category = Mage::getModel('catalog/category')->load($_cat);
$prodCollection = $category->getProductCollection()->getAllIds();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.