Custom sort field for Magento products listing

Today we are going to change Magento default products displaying order. I mean “sort by” field and it’s direction. This article will show how to add a new sorting field, called “Date added” to the products list.
First of all, we need to create a new module. Don’t worry, it is going to be a very simple extension. This way our customization will work after Magento upgrade. So we just need to rewrite Mage_Catalog_Model_Config model class and Mage_Catalog_Block_Product_List_Toolbar block class.
Module configuration file app/code/local/Atwix/Tweaks/etc/config.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <Atwix_Tweaks>
            <version>1.0</version>
        </Atwix_Tweaks>
    </modules>
    <global>
        <blocks>
            <tweaks>
                <class>Atwix_Tweaks_Block</class>
            </tweaks>
            <catalog>
                <rewrite>
                    <product_list_toolbar>Atwix_Tweaks_Block_Product_List_Toolbar</product_list_toolbar>
                </rewrite>
            </catalog>
        </blocks>
        <models>
            <catalog>
                <rewrite>
                    <config>Atwix_Tweaks_Model_Catalog_Config</config>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>

In Atwix_Tweaks_Block_Product_List_Toolbar we just define default direction, app/code/local/Atwix/Tweaks/Block/Product/List/Toolbar.php:

<?php
class Atwix_Tweaks_Block_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar
{
    protected $_direction = 'asc';
}

In Atwix_Tweaks_Model_Catalog_Config class we rewrite getAttributeUsedForSortByArray function to add custom sorting fields,
app/code/local/Atwix/Tweaks/Model/Catalog/Config.php:

<?php

class Atwix_Tweaks_Model_Catalog_Config extends Mage_Catalog_Model_Config
{
    public function getAttributeUsedForSortByArray()
    {
        $options = array(
            'created_at' => Mage::helper('catalog')->__('Date Added')
        );

        foreach ($this->getAttributesUsedForSortBy() as $attribute) {
            $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
        }

        return $options;
    }
}

Note, that you can add your own fields to $options array.
The last step is to enable our module, app/etc/modules/Atwix_Tweaks.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <Atwix_Tweaks>
            <active>true</active>
            <codePool>local</codePool>
        </Atwix_Tweaks>
    </modules>
</config>

Now you can see changes at the frontend.
The source code can be found here. We hope that this post will help you with coding. That’s all for now, stay tuned.