Magento 1.9 – How to Display Search Results Sorted by Categories

catalogsearchcategorymagento-1.9sorting

I need to sort my search results by product categories.

If I have Product A and Product B in Category A
And I have Product C and Product D in Category B

If all products are available in search result, I want to show them like,

Product A, Product B, Product C, Product D

I want to put same category products with each other on results page.

Currently It is showing as

Product A, Product C, Product B, Product D

I have tried this but its not working.

Best Answer

The reference you are using is not working is because there is no code to sort the products by category. You need to override Mage_CatalogSearch_Block_Result::_getProductCollection() and then add sorting function in it to show results in order of category id.

Try with below. Use the same reference and add this additional function to the same file.

protected function _getProductCollection()
{
    if (is_null($this->_productCollection)) {
        $this->_productCollection = $this->getListBlock()->getLoadedProductCollection();
    }
    $listOrder = $this->getRequest()->getParam('dir') ? $this->getRequest()->getParam('dir') : 'desc';
    if(!$this->getRequest()->getParam('order') || $this->getRequest()->getParam('order') == 'category'){
        $this->_productCollection->getSelect()->joinLeft(array('category' => Mage::getSingleton('core/resource')->getTableName('catalog_product_category')),'e.entity_id = category.product_id', array('category_id'))->group('e.entity_id')->order('category.category_id '.$listOrder);
    }
    return $this->_productCollection;
}
Related Topic