Apply custom conditions on faceted data elastic search collection before it returns field faceted data from the faceted search results in Magento 2.
From the Magento 2.4, Elasticsearch is the Primary search engine instead of Deprecated Mysql.
When you go to the Catalog search module, FullText collection class, you can check the getFacetedData()
method to return the field with faceted search results. Using Before plugin, you can add custom conditions before final search results render on the page.
create an etc/di.xml
for the plugin definition,
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection"> <plugin name="add_custom_conditions" type="Jesadiya\FacetedSearch\Plugin\BeforeFacetResults" /> </type> </config>
Create a Plugin file to add your conditions on product collection,
<?php namespace Jesadiya\FacetedSearch\Plugin; use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection; class BeforeFacetResults { /** * Add custom condtions before get faceted data * * @param Collection $productCollection * @param string $field * @return array */ public function beforeGetFacetedData(Collection $productCollection, $field): array { //CUSTOM_CONDITIONS_ON_PRODUCT_COLLECTION //$productCollection->addFieldToFilter('MY_FIELD', 'VALUE'); return [$field]; } }
You have to apply your required conditions to the product collection before the faceted search result will be loaded.
Based on your custom conditions, the result will be loaded for the catalog search page on the front end.