Magento: Sort Newest products by ‘created date’and ‘new from date’

Well, through this write-up, I will let you know about an extension that enables the catalog to be sorted by the newest products. The extension is known as EWTechnologies_SortByNewest, and came to my notice when the toolbar was debugged for not displaying the pagination links. I had a deep look into it and was taken aback to find it overriding the default.

Mage_Catalog_Block_Product_List_Toolbar class but extending from Mage_Page_Block_Html_Pager.

The Mage_Eav_Model_Config class was completely overridden. This one was greatly changed in the Magneto’s later versions, so the override executes very old code. I found it very dangerous to keep albeit there weren’t any other visible detrimental effects. It is definitely not the best way to sprint obsolete code in any case.

I decided this feat does not need overriding as much as core code does; therefore I looked into it more deeply and came out with the solution that wasn’t too tough and did not entail overriding any core code per se.

Here is the code to sort/order product by both created date and new from date:-

$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);

$collection = Mage::getModel(‘catalog/product’)
->getCollection()
->addAttributeToFilter(‘news_from_date’, array(‘date’ => true, ‘to’ => $todayDate))
->addAttributeToFilter(‘news_to_date’, array(‘or’=> array(
0 => array(‘date’ => true, ‘from’ => $todayDate),
1 => array(‘is’ => new Zend_Db_Expr(‘null’)))
), ‘left’)
->addAttributeToSort(‘news_from_date’, ‘desc’)
->addAttributeToSort(‘created_at’, ‘desc’);

Conclusion

This approach functions on any Magento CE version more than 1.4 and PE and EE versions. The standalone problem arising out of it relates to a future Magento upgrade that upgrades created_at attribute, it gets quite easy to reapply the database edits for restoring functionality simpler than troubleshoot problems with core code overrides.

Magento Authority delivers quality Magento development services through its extensively experienced Magento professionals who are result-oriented.

Comments are closed.