Add Filter to getLoadedProductCollection() in Magento

attributesce-1.9.0.0collection;product

In my magento store (ce-1.9.0) I have setup a custom product attribute:

custom_depth_check

And the attribute has the setting of

Used in Product Listing : Yes
Used for Sorting in Product Listing : Yes

I now need to filter any getLoadedProductCollection() with this attribute. The attribute will either be set at:

null
0
1

I need to filter all instances of getLoadedProductCollection() so that it will EXLCUDE any products with

custom_depth_check : 1

I have tried to clear and reload like so:

$_productCollection=$this->getLoadedProductCollection()
->clear()
->addAttributeToFilter('custom_depth_check', array('neq' => 1));

But that results in an empty collection. I also tried adding ->load() at the end but again nothing comes up.

I have to stored this collection into an array for specific field such as name, price, description, images etc.

how can i achieve this.

Best Answer

The issue is that Mage_Catalog_Block_Product_List:getLoadedProductCollection returns a loaded product collection. Meaning that it has already had all filters applied to it etc and has actually run the query.

To add new parameters to this query you need to rewrite/override Mage_Catalog_Model_Layer::prepareProductCollection and pop your extra filters in right below the filters already present. Make sure it's above the addMInimumPrice etc as one of these is going to be the thing causing your collection to be loaded.

You can see the instruction here on how to rewrite this block (How to Override Mage_Checkout_Block_Links).

An alternative (and my preferred solution) is to create a new block extending the Mage_Catalog_Block_Product_List and make a layout xml update to tell the code to use your block.

Either way, that's all that needed. Glad to have helped.