Magento: Sort search results by newest first

I recently (well, a few months ago) started working for online retail company prettylittlething.com.  Since then I’ve been getting back into the Magento way of doing things (along with managing their IT infrastructure… but that’s a whole other set of posts) and decided I might as well publish some of the minor tips and bits of code I’ve worked on.

Today I have a module that ‘fixes’ the default search order in magento.

By default, when you do a search in magento the results are shown in ascending order of creation.  IE: older products are shown first.  Now, I’m sure there’s some obscure reason why this is so (although it could just be that with no search order defined they’re pulled out in the order they went into the database) but anyway, after some googling and a bit of tinkering I have a fix for it.

The search order / direction is set in ‘Mage_CatalogSearch_Block_Result’ (located in app/code/core/Mage/CatalogSearch/Block/Result.php).  This module just overrides that class and rewrites the following method:

public function setListOrders()
    {
        $category = Mage::getSingleton('catalog/layer')
            ->getCurrentCategory();
        /* @var $category Mage_Catalog_Model_Category */
        $availableOrders = $category->getAvailableSortByOptions();
        unset($availableOrders['position']);
        $availableOrders = array_merge(array(
            'relevance' => $this->__('Relevance'),
	    'entity_id' => $this->__('EntityId') //**add entity_id to allowed orders**
        ), $availableOrders);

        $this->getListBlock()
            ->setAvailableOrders($availableOrders)
            ->setDefaultDirection('desc')
            ->setSortBy('entity_id'); //**set default sort to entity_id**
        return $this;
    }

You can see I’ve commented my additions to this function, it’s just a couple of lines.

You can grab the download below, and see it in action on PrettyLittleThing.com here




4 Comments

Hi Larry, unfortunately I had some issues when changing hosting provider and it looks like the files for this module were lost. I may try to recreate them at some point, but this isn’t a priority for me at the moment. I am available for contract work if this is still an issue for you.

Leave a Reply

Your email address will not be published. Required fields are marked *