Search code examples
phpsortingmagentocollectionsmagento-1.6

Magento Quick Search - showing results from given category first


I'm looking to have the normal quick search, with the addition of one feature: results from a given category come first.

So far I have modified protected function _getProductCollection() in Mage_CatalogSearch_Block_Result and this works, but it ignores the custom search results (e.g. by price or name) which I want to be applied within the two groups of results.

My additional code is:

$initial = $this->_productCollection->getAllIds();
$this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load(3));

$newids = $this->_productCollection->getAllIds();//$this->_productCollection->getAllIds();

$merged_ids = array_merge($newids, $initial);
$merged_ids = array_unique($merged_ids);

$this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load(2));

$this->_productCollection->getSelect()->order("find_in_set(e.entity_id,'".implode(',',$merged_ids)."')"); 

Where cat 2 is the root category.

So, where is the collection being sorted? If I move this there that should do the trick I believe (?).


Solution

  • It may not work in everyone's situation, but adding the following worked for me:

    $this->_productCollection->setOrder($this->getRequest()->getParam('order'), $this->getRequest()->getParam('dir'));
    

    So I ended up with a protected function _getProductCollection() of:

    protected function _getProductCollection()
    {
        if (is_null($this->_productCollection)) {
            $this->_productCollection = $this->getListBlock()->getLoadedProductCollection();
        }
        $this->_productCollection->setOrder($this->getRequest()->getParam('order'), $this->getRequest()->getParam('dir'));
        $initial = $this->_productCollection->getAllIds();
        $this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load(3));
    
        $newids = $this->_productCollection->getAllIds();//$this->_productCollection->getAllIds();
    
        $merged_ids = array_merge($newids, $initial);
        $merged_ids = array_unique($merged_ids);
    
        $this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load(2));
    
        $this->_productCollection->getSelect()->order("find_in_set(e.entity_id,'".implode(',',$merged_ids)."')"); 
    
        return $this->_productCollection;
    }