Wednesday, May 02, 2012

Get Specific Category Product by ID in Magento


This one is collected from a blog:


<?php
$category_id = 2246;     //where $category_id is the id of the category
$catagory_model = Mage::getModel(‘catalog/category’)->load($category_id);
$collection = Mage::getResourceModel(‘catalog/product_collection’);
$collection->addCategoryFilter($catagory_model); //category filter
$collection->addAttributeToFilter(‘status’,1); //only enabled product
$collection->addAttributeToSelect(array(‘name’,'url’,'small_image’));
//add product attribute to be fetched
//$collection->getSelect()->order(‘rand()’); //uncomment to get products in random order
$collection->addStoreFilter();
if(!empty($collection))
{
foreach ($collection as $_product):
echo $_product->getName();           //get product name
echo $_product->getId();              //get product id
echo $_product->getSmallImageUrl();    // get product Image URL
echo $_product->getProductUrl();     // get product description page URL
echo $_product->getSku();            // get product SKU
endforeach;
}    else    {
echo ‘No products exists’;
}
?>

No comments: