How to apply custom conditions for product collection in Magento 2?

In Magento 2, There are some situations where you need to set custom conditions for layered(filter) navigation. In Magento 2, All product collection comes from Catalog Module at Layer.php file from vendor/magento/module-catalog/Model/Layer.php.
Layer.php file has a function called getProductCollection() and its responsibility for getting all product collection in listing page.

While you gave custom conditions for getProductCollection() collection, You got all the product based on custom conditions you applied but that custom conditions don’t apply to Filter(Layered) Navigation to the listing.

If you are dealing with custom conditions in listing page and your conditions don’t apply to layered navigation filter.

When customer faced a problem for filtering in the listing, its feel bad experience for the site and for overcoming this issue for layered navigation we need to sort out the issue for run smooth functionality on the page.

After debugging we have found the actual file where custom conditions are worked for layered navigation.

If you want to give custom conditions for layered navigation you need to go for core file in Catalog Search Module, vendor/magento/module-catalog-search/Model/Search/IndexBuilder.php

build() function is the responsible for getting layered navigation content in listing and search result page from IndexBuilder.php

For Apply custom conditions to layered navigation, you need to override build() function.  I hope you have a custom module with basic skeletons like registration.php and module.xml file,

File path,
app/code/Rbj/FilterSearch/etc/frontend/di.xml

File Path,
app/code/Rbj/FilterSearch/Plugin/CatalogSearch/Model/Search/IndexBuilder.php

You can give your custom filter conditions in aroundBuild() function in the above file.
Where $select = $proceed($request); Its display actual default query of Magento and you can give some extra conditions to based on your requirement.

Once You gave conditions to the above plugin you don’t need to give conditions or override getProductCollection() function.

 

One Reply to “How to apply custom conditions for product collection in Magento 2?”

  1. It seems like this is not working in Magento 2.3.0. If possible, may you please update the check and update the blog with the required changes.

Leave a Reply

Your email address will not be published. Required fields are marked *