Magento 1.7 – How to Add Custom Product to Catalog Search Collection

catalogsearchmagento-1.7product-collectionsearch

Currently I am trying to add some custom products on CatalogSearch collection . For this I am working on Mage_CatalogSearch_Model_Layer. I know that its core part of Magento but whenever I 'll get any success on this code I will override CatalogSearch_Model.

Rightnow I am working on this method

 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();

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

// my custom code start

$collection2 = Mage::getModel('catalog/product')->getCollection()->addFieldToFilter('entity_id', array(1,2));

$collectiondata=$collection2->getData();

foreach($collectiondata as $customdata)
{
$collection->addItem($customdata);
}

        return $this;
    }

With this code I can able add my custom product into the original collection but It create an Issue on catalog search result. It Means If in search result original product found then it successful works otherwise not.

Any help will be appreciated

Thank you

Best Answer

It might be because it's an empty collection. Without further testing I wouldn't know for sure. But maybe give this a try

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


    $extra_collection = Mage::getResourceModel('catalog/product_collection')
                            ->addFieldToSelect('entity_id')
                            ->addFieldToFilter('entity_id', array(1,2));

    $collection_ids = array_merge($collection->getAllId(), $extra_collection);

    $collection = Mage::getResourceModel('catalog/product_collection')
                            ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
                            ->addFieldToFilter('entity_id', $collection_ids);


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

    return $this;
}
Related Topic