How to Filter Category List by Custom Product Attribute in Magento

magento-1.9

I have two different headers in my Magento one for retail shop and second is for commercial shop in same store view. In both header Product category will be same.

  • Condition #1 :- In retail shop when we click on "Products" category then it will be list all products.
  • Condition #2 :- when I will change click on commercial shop header then it will be show only commercial products I have assigned custom attribute for it.
    Is this possible ?

I found code for loaded product collection in this file \app\code\core\Mage\Catalog\Block\Product\List.php can we add attribute filter in this function ?

protected function _getProductCollection()
    {
        if (is_null($this->_productCollection)) {
            $layer = $this->getLayer();
            /* @var $layer Mage_Catalog_Model_Layer */
            if ($this->getShowRootCategory()) {
                $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
            }

            // if this is a product view page
            if (Mage::registry('product')) {

                // get collection of categories this product is associated with
                $categories = Mage::registry('product')->getCategoryCollection()
                    ->setPage(1, 1)
                    ->load();

                // if the product is associated with any category
                if ($categories->count()) {
                    // show products from this category
                    $this->setCategoryId(current($categories->getIterator()));
                }
            }

            $origCategory = null;
            if ($this->getCategoryId()) {
                $category = Mage::getModel('catalog/category')->load($this->getCategoryId());
                if ($category->getId()) {
                    $origCategory = $layer->getCurrentCategory();
                    $layer->setCurrentCategory($category);
                    $this->addModelTags($category);
                }
            }
            $this->_productCollection = $layer->getProductCollection();

            $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

            if ($origCategory) {
                $layer->setCurrentCategory($origCategory);
            }
        }

        return $this->_productCollection;
    }

Best Answer

For your second Condition you can Filter Your Product Collection Like This :-

$products=Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToFilter('your_custom_attribute_code', 'your_custom_attribute_value');

You Can Add this filter at File list.php

app\code\core\Mage\Catalog\Block\Product\List.php Find The setCollection method

and under $this->_productCollection = $collection;

add this code

$collection->addAttributeToFilter('your_custom_attribute_code', 'your_custom_attribute_value');

Related Topic