0

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...
};
2

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.

2
  • Thanks for this. My categories are mostly non anchors so approach 2 is great. I've just realised though that it is showing me products in either 63 OR 71 - i need to only show products in BOTH. Is this possible?
    – odd_duck
    Jul 3 '14 at 14:17
  • @odd_duck. I don't think you can filter by 2 categories. not this way at least.
    – Marius
    Jul 3 '14 at 14:23

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.