Magento Sort By Newest Products Made Easy
The Situation
Recently, I had the pleasure of working on an existing site we took over. The site had been upgraded from Magento CE to EE before it came to me. One of the tasks was to make a new enterprise theme and clean up any unused or incompatible extensions.
I will just focus on one extension here that was added to allow the catalog to be sorted by newest products. This is the EWTechnologies_SortByNewest. It came to my attention after debugging the toolbar for not showing the pagination links where there is more than one page of products. So I looked into it and to my horror realized that it was overriding the default Mage_Catalog_Block_Product_List_Toolbar class but extending from Mage_Page_Block_Html_Pager. If that wasn’t bad enough, it was also completely overriding the Mage_Eav_Model_Config class. This one has been substantially changed in later versions of Magento so the override implements very old code. I decided that this is too risky to keep even though there were no other visible adverse effects. It certainly isn’t best practice to run outdated code in any case.
I thought this feature shouldn’t require overriding so much core code so I investigated and, to my delight, found that the solution was very simple and quite elegant and didn’t involve overriding any core code as such.
The Approach
The Product Entity in Magento has a ‘created_at’ attribute which stores the date when the product was created. Logically, it lends itself to be used for the sort by newest feature as it is set only once by the system, when the product was created.
A look into the eav_attribute table gives us the attribute_id and an inspection of the catalog_eav_attribute table shows that the attribute is set to not be used in the sort by drop-down. So, the obvious course of action was to set the attribute’s used_in_sort_by field to 1 and then the only other thing left was to update the frontend_label in eav_attribute to read “Newest”. That’s all, folks!
The Extension
I’ve whipped up a quick extensions that will perform those updates and makes it easy to install on any site that needs this feature.
Comments
Post a Comment