0

Im using a code to get a product collection from a specific category, but if the category is inactive it returns empty to me.

Is there a way to retrieve the products even if the category is inactive?

Here is the code:

$category = new Mage_Catalog_Model_Category();
$category->load(111); //cat_id
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');

It works fine on active categories.

Thanks,

1 Answer 1

2

Welcome to Magento.SE! A few things here:

Firstly:

Instead of doing this:

$category = new Mage_Catalog_Model_Category();
$category->load(111); //cat_id

Do this:

$category = Mage::getModel('catalog/category')->load(111);

The reason being is that you get the benefit of Magento's rewrite system - that way you know you're always using the registered rewrite.

Second:

Instead of loading the category and then loading products, rather load the product collection and filter by category association:

$category = Mage::getModel('catalog/category')->load(111);
$collection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addCategoryFilter($category)
    ->addAttributeToSelect('*');

You could optimize this by filtering only by category id and not loading the category at all:

$categoryId = 35;
$collection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('category_ids',array('finset'=>$categoryId));
1
  • Whoa thanks, that was a really good response. Actually i dont know why i created a new SE account, will track back into it. I had fixed it, but i will use your solution
    – Beoulve
    Commented Aug 16, 2013 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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