cancel
Showing results for 
Search instead for 
Did you mean: 

Incorrect product count in layered navigation after overriding list product collection.

SOLVED

Re: Incorrect product count in layered navigation after overriding list product collection.

apply below solution to solve elastic search issue.

 

 

Spoiler
create di.xml file on path app/code/Namespace/Modulename/etc/frontend
<type name="Magento\Elasticsearch7\Model\Client\Elasticsearch">
    <plugin name="elastcisearch_filter_plugin" type="Namespace\Modulename\Model\Plugin\ElasticLayerPlugin" />
</type>
Spoiler
Now we need to create "ElasticLayerPlugin.php" on path app/code/Namespace/Modulename/Model/Client
    namespace Namespace\Modulename\Model\Plugin;

class ElasticLayerPlugin
{
	protected $helperObj;
	
	public function __construct(
		 \Namespace\Modulename\Helper\Data $helperObj
	) 
	{
		 $this->helperObj = $helperObj;
	}
	
	public function beforeQuery($subject,$query) 
	{
		$productIds   = $this->helperObj->filterCollectionIds();

		
		// Add the product ids to filter the Elasticsearch product collection
		
		$query['body']['query']['bool']['filter'] = ['ids' => [ 'values' => $productIds]];

		return [$query];
	}
}

 

 

 

Re: Incorrect product count in layered navigation after overriding list product collection.

Please update the code of the following helper file

 

\Namespace\Modulename\Helper\Data $helperObj

 

 

Thank you

Re: Incorrect product count in layered navigation after overriding list product collection.

app/code/Vendor/Module/Helper/Data.php

 

 
<?php
namespace Vendor\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
 public $listProductBlock;
  public function __construct(    Context $context,
    \Magento\Catalog\Block\Product\ListProduct $listProductBlock
) {       
    $this->listProductBlock  = $listProductBlock;     
    parent::__construct($context);
  }
public function filterCollectionIds(){
    $productCollection = $this->listProductBlock->getLoadedProductCollection();
    $productCollection->addAttributeToFilter('custom_attribute', array('eq' => "No"));
   $filteredIds = array();
    foreach($productCollection as $product){
        $productId = $product->getId();
       $filteredIds[] = $productId;
    }
    return $filteredIds;
  }

}

Reference: https://magento.stackexchange.com/questions/349836/custom-condition-for-elastic-search-collection-in...