Magento - catalog search by product name should redirects to product details page

Affected File : app/code/core/Mage/CatalogSearch/Model/Layer.php

Below function is changed.

public function prepareProductCollection($collection)
{
    $collection
        ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
        ->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())
        ->setStore(Mage::app()->getStore())
        ->addMinimalPrice()
        ->addFinalPrice()
        ->addTaxPercents()
        ->addStoreFilter()
        ->addUrlRewrite();

    /*================== condition added ==========================*/

    $product = Mage::getModel('catalog/product')
        ->loadByAttribute('name', Mage::helper('catalogsearch')->getQuery()->getQueryText());

    if($product && ($product->getStoreId() == Mage::app()->getStore()->getStoreId()))
    {
        //Below 3 lines of code redirects to the product details page
        $url = $product->getProductUrl();
        Mage::app()->getFrontController()->getResponse()->setRedirect($url);
        return;

        //Comment above 3 lines of code to stop redirects to the product details page
        //And uncomment below line to filter collection by product name exactly
        //$collection->addAttributeToFilter('name', array('eq' => Mage::helper('catalogsearch')->getQuery()->getQueryText()));
    }

    /*=============================================================*/

    Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
    Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);

    return $this;
}

3 comments: