Magento – How to Get New Products List from Specific Category with Widget in CMS

cmswidgets

Is there any way to get New Products List from specific Category with Widget in CMS Pages? I have tried specifying category ID using category_id="12" but it is pulling latest products from all the categories.

Below is the Widget code which I am using:

{{widget type="catalog/product_widget_new" category_id="12" products_count="4" template="catalog/product/widget/new/content/new_grid.phtml"}}

Best Answer

The new products widget does not support filtering by category.
but you can create your own block [module]/product_new that extends Mage_Catalog_Block_Product_New.
the only thing you need to add in your block are these methods.

//category member var
protected $_category = null;
//load the category
public function getCategory() {
    if (is_null($this->_category)) {
        if ($this->hasData('category_id')) {
            $category = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($this->getData('category_id'));
            if ($category->getId()) {
                 $this->_category = $category;
            }
        }
        //if the category is not valid set it to false to avoid loading it again.
        if (is_null($this->_category)) {
            $this->_category = false;
        }
    }
    return $this->_category;
}
//override the _beforeToHtml() method
protected function _beforeToHtml() {
    parent::_beforeToHtml();
    //if a category is specified filter by it.
    if ($this->getCategory()) {
        $this->getProductCollection()->addCategoryFilter($this->getCategory());
    }
    return $this;
}
//Change the cache key so you won't get the same products for different categories when the cache is on
public function getCacheKeyInfo()
{
    $cacheKeyInfo = parent::getCacheKeyInfo();
    if ($this->getCategory()) {
         $cacheKeyInfo[] = $this->getCategory()->getId();
    }
    else {
         $cacheKeyInfo[] = 0;
    }

    return $cacheKeyInfo;
}

Now all you need to do is use your block in the {{block}} directive

{{widget type="[module]/product_new" category_id="12" products_count="4" template="catalog/product/widget/new/content/new_grid.phtml"}}