Josh Pennington
Josh Pennington

Reputation: 6408

Magento Product Collection Get Only Products From Certain Categories

I am trying to get a list of products that have a sale price that are only in certain categories. Right now I am trying to use a product collection to get this data. I am not sure how I would go about restricting the collection for particular categories only. Here is what I have so far:

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('special_price', array('neq' => ""))
    ->addAttributeToFilter('discontinued', array('neq' => 1))
    ->setPageSize(10)
    ->setOrder('price', 'ASC')
    ;

The discontinued attribute is a custom attribute that we use so that products don't display but also don't 404.

Is there a way to use the product model and restrict to certain categories?

Upvotes: 5

Views: 8999

Answers (1)

Josh Pennington
Josh Pennington

Reputation: 6408

Figured it out. You start with the category and get the product collection from the category and then refine it down from there. In code it looks like this:

$products = Mage::getModel('catalog/category')->load(410)
    ->getProductCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('special_price', array('neq' => ""))
    ->addAttributeToFilter('discontinued', array('neq' => 1))
    ->setOrder('price', 'ASC')
    ;

Upvotes: 5

Related Questions