3

I'm using Magento EE Lite (1.11.02) and I'm trying to load a collection of products by one single category. The following code functions as you would expect:

public function getProductList()
{
    $products = Mage::getModel('catalog/category');
    $productslist = $products->getProductCollection()->addAttributeToSelect('*');

    foreach($productslist as $product)
    {
        echo 'name: ' . $product->getName() . '<br/>';
    }
}

It outputs the name of every product in the catalog (including the products in the category I'm trying to select in future examples). But as soon as I try to add any kind of category filter:

public function getProductList()
{
    $products = Mage::getModel('catalog/category')->load(3);
    $productslist = $products->getProductCollection()->addAttributeToSelect('*');

    foreach($productslist as $product)
    {
        echo 'name: ' . $product->getName() . '<br/>';
    }
}

or:

public function getProductList()
{
    $products = Mage::getModel('catalog/category');
    $productslist = $products->getProductCollection()->addAttributeToSelect('*')
        ->addCategoryFilter(3);

    foreach($productslist as $product)
    {
        echo 'name: ' . $product->getName() . '<br/>';
    }
}

It doesn't output anything. No errors, it just acts the way it would if zero products were loaded.

The products are in a subcategory of a root category. I've tried different categories, creating new categories, populating them with new items, I've checked their visibility, their status, I've tried a dozen different code snippets, nothing ever works.

Is there something wrong with my code? Is there some setting in categories that could cause it to be unfilterable? I'm running out of ideas, any help is very appreciated.

migrated from stackoverflow.com Aug 2 '13 at 17:11

This question came from our site for professional and enthusiast programmers.

3

Try it like this:

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
$category = Mage::getModel('catalog/category')->load(3);//or any other id
$products->addCategoryFilter($category);
foreach ($products as $product){
    echo 'name: ' . $product->getName() . '<br/>';
}

The method addCategoryFilter expects as parameter an instance of Mage_Catalog_Model_Category

public function addCategoryFilter(Mage_Catalog_Model_Category $category)
  • 1
    That wasn't the problem, but thanks for the tip about the addCategoryFilter param. The problem was I was trying to access subcategories of a root category that my store wasn't set to use. I'll post a full detailed answer tomorrow if I can, just in case this gets searched. – Jack Benny Aug 2 '13 at 17:47

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.