Magento : set list sort order for categories and search

Big online shops have a lot of users, and as such they can afford to try features that most novice users won't even understand : that is the case for the sort order for lists, that in Magento displays name, price and relevance. It is very nice to have that feature but in my customer's case the default list was ordered by "best choice", which doesn't mean a lot to users. Of course, the magento configuration allows to set the list default order, but that only works for categories, not for search. And that is a big problem because search results should be ordered by relevance : that is the principle of the search.

I decided to work on search and installed the better store search plugin, which after a few hours of hard work on my magento install gave me full satisfaction. But to my surprise, it is not the plugin itself which gave me hard work, but magento 's undocumented feature of list sorting. Here is what I did to get my search results ordered by relevance descending always 


  • Magento configuration : I display onlists
  • view/lists.phtml  . removed the toolbar display
  • extension  : wrote my own Mage_Catalog_Product_List extension that overrides the session / default valur for the sort order :
     class Webmsterbulletin_Catalog_Block_Product_List   extends Mage_Catalog_Block_Product_List 
    function  _getProductCollection() {
         if (strstr($_SERVER["REQUEST_URI"], "catalogsearch")) 
         {$orderField="relevance";$orderOrder="desc";} else {$orderField="name";$orderOrder="asc";}
         Mage::log($_SERVER["REQUEST_URI"] . $orderField,null,'layout.log');
           return  parent::_getProductCollection()
           ->setOrder($orderField, $orderOrder);
           //->addAttributeToSort('relevance', 'desc');
           // return  parent::_getProductCollection()->setOrder('name', 'ASC');

    What's happening here ? as you can see I rely (very bad practise) on the good old php_self  variable to detect if we are in the processs of returning search results. If so, then we set the order to relevance desc, otherwise we go name ascending, you could go price ascending too if you wanted !!

  • Oh, last but not least, the config.xml  that overrides  Mage_Catalog_Product_List :
    <?xml version="1.0"?>  
1 reply
  1. Dan Norris
    Dan Norris says:

    Hi, nice tutorial!
    Just a quick note as I was recently caught out by it, the plugin you're using (Crayon) to display code, is converting both to their HTML characters.



Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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