Tuesday, February 17, 2015

How to show custom collection with layered navigation in Magento ?

Sometime you need to show all special price products collection or any custom product collection of any categories, under selected category (eg. Special) with layered navigation.

copy /app/code/core/Mage/Catalog/Model/Layer.php to /app/code/local/Mage/Catalog/Model/Layer.php

Go to line# 97

Replace following function code

public function getProductCollection()
    {
        if (isset($this->_productCollections[$this->getCurrentCategory()->getId()])) {
            $collection = $this->_productCollections[$this->getCurrentCategory()->getId()];
        } else {
            $collection = $this->getCurrentCategory()->getProductCollection();
            $this->prepareProductCollection($collection);
            $this->_productCollections[$this->getCurrentCategory()->getId()] = $collection;
        }

        return $collection;
    }

with

public function getProductCollection()
    {
        if (isset($this->_productCollections[$this->getCurrentCategory()->getId()]))
        {
            $collection = $this->_productCollections[$this->getCurrentCategory()->getId()];
        }
    else
    {
        //custom code start
        if($this->getCurrentCategory()->getId() == '228')
        {
            $collection = Mage::getResourceModel('catalog/product_collection');
            $todayDate = date('m/d/y');
            $tomorrow = mktime(0, 0, 0, date('m'), date('d'), date('y'));
            $tomorrowDate = date('m/d/y', $tomorrow);

            $collection->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $todayDate))
                ->addAttributeToFilter('special_to_date', array('or'=> array(
                    0 => array('date' => true, 'from' => $tomorrowDate),
                    1 => array('is' => new Zend_Db_Expr('null')))
                ), 'left');

            $this->prepareProductCollection($collection);
            $this->_productCollections[$this->getCurrentCategory()->getId()] = $collection;
        //custom code end
        }

        else
        {

            $collection = $this->getCurrentCategory()->getProductCollection();
            $this->prepareProductCollection($collection);
            $this->_productCollections[$this->getCurrentCategory()->getId()] = $collection;
        }

    }

Enjoy!!!

No comments:

Post a Comment