Category Collection Error – Fix Call to getId() on Non-Object

categorycollection;error

I have the following code which shows 5 products from the current category (which has cat ID:63):

$_helper    = $this->helper('catalog/output');
$_category  = $this->getCurrentCategory();   
$collection = $_category->getProductCollection();
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$numProducts = 5;
$collection->setPage(1, $numProducts)->load();

This works fine but i want to adjust this further so it only show products that are also found in another category (cat ID:71) with $collection->addCategoryFilter(71); but when i do this i get the error:

Fatal error: Call to a member function getId() on a non-object in

Full code is:

$_helper    = $this->helper('catalog/output');
$_category  = $this->getCurrentCategory();   
$collection = $_category->getProductCollection();
Mage::getModel('catalog/layer')->prepareProductCollection($collection);

// this line throws the error
$collection->addCategoryFilter(71);

$numProducts = 5;
$collection->setPage(1, $numProducts)->load();


foreach($collection as $_product){
    // output products...
};

Best Answer

addCategoryFilter does not work with an integer parameter. It expects a Mage_Catalog_Model_Category or at least a Varien_Object.

So you have to do this:

$category = Mage::getModel('catalog/category')
         ->setStoreId(Mage::app()->getStore()->getId())
         ->load(71);
$collection->addCategoryFilter($category);

If you don't want to load the category object for performance reasons you can do this:

$obj = new Varien_Object();
$obj->setId(71);
$collection->addCategoryFilter($obj);

The down side of this second approach is that if the category with id 71 has is_anchor set to true then it won't be taken into consideration.
To overcome that use this:

$obj = new Varien_Object();
$obj->setId(71);
$obj->setIsAnchor(1);
$collection->addCategoryFilter($obj);

The down side of this third approach is the exact opposite of the second one. If the category is not an anchor it will be treated as an nachor category.

Related Topic