Magento – Get product collection from a category id

collection;magento-1product-collection

I am trying to get a collection of products from a category id. A few things I have tried are in the block :

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

and

    $category = Mage::getModel('catalog/category')->load(123);
    $products = $category->getProductCollection()->addCategoryFilter($category)
                         ->addAttributeToFilter('type_id', 'simple')
                         ->addAttributeToSelect('*');

also tried just doing it from the phtml

$oCatId = Mage::getModel('catalog/category')->load(769); 
        $products->addCategoryFilter($oCatId);

None of this works but I am not seeing any errors either. I saw another post that seems like the same question : Magento – Get Products from Specific Category but that method did not work for me either. Thanks for any help!

Best Answer

Try this:

$products = Mage::getModel('catalog/category')->load($category_id)
 ->getProductCollection()
 ->addAttributeToSelect('*') // add all attributes - optional
 ->addAttributeToFilter('status', 1) // enabled
 ->addAttributeToFilter('visibility', 4) //visibility in catalog,search
 ->setOrder('price', 'ASC'); //sets the order by price

Source: http://overlycaffeinated.com/blog/2011/02/get-all-sale-products-from-a-category-in-magento/

This should work because it adds the category filter for you by virtue of already having the category loaded:

Mage_Catalog_Model_Category

public function getProductCollection()
{
    $collection = Mage::getResourceModel('catalog/product_collection')
        ->setStoreId($this->getStoreId())
        ->addCategoryFilter($this);
    return $collection;
}

Wait, it still doesn't work!

Ok, so you may have larger issues, presumably something overwriting getProductCollection. So let's try circumventing that convenience method:

$category = Mage::getModel('catalog/category')->load($category_id);
$products = Mage::getResourceModel('catalog/product_collection')
        ->setStoreId(Mage::app()->getStore()->getId())
        ->addCategoryFilter($category);