简体   繁体   中英

Add custom attribute to filter in product collection in magento

I need to add custom attribute to filter for product collection

I tried below code but filter is not working

$_productCollections=$this->getLoadedProductCollection();
$_productCollection = $_productCollections->addAttributeToFilter('weight', array('lt' => 100));

below code is working

$collection = Mage::getModel('catalog/product')->getCollection();
$_productCollection = $collection->addAttributeToFilter('weight', array('lt' => 100));

I need proper way to add filter range for weight attribute like

->addAttributeToFilter('weight', array('lt' => 100));

in default product collection( $this->getLoadedProductCollection(); )

I have one solution for this question

Step1:

Duplicate block code for list

\app\code\core\Mage\Catalog\Block\Product\List.php to 
\app\code\local\Mage\Catalog\Block\Product\List.php

Step2:

Change below code from

$this->_productCollection = $layer->getProductCollection();

to

$this->_productCollection = $layer->getProductCollection()->addAttributeToFilter('weight', array('lt' => 100));

This is one simple solution to resolve your issue properly.

Try explicitly selecting the attribute with:

$_productCollection->addAttributeToSelect('weight');

And then the filtering:

$_productCollections->addAttributeToFilter('weight', array('lt' => 100));

Another way is selecting by default the attribute in the product collection, by placing this in the config.xml of your module:

<config>
<frontend>
     <product>
          <collection>
               <attributes>
                  <weight />
               </attributes>
          </collection>
      </product>
</frontend>

Then you should be able to do the filter as usual:

$_productCollections->addAttributeToFilter('weight', array('lt' => 100));

Maybe, collection is already loaded. Add filter before loading collection

($this->_getProductCollection()->load())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM