How we can hide out-of-stock products for specific categories only? The below code is working with Magento 2.3 version after upgrading to 2.4.5 it is not working due to stock management having moved to MSI (Multi-Source Inventory).
di.xml
<?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\Search\IndexBuilder">
<plugin name="Vendor_CustomCategoryCollection::CustomLayernavigation"
type="Vendor\CustomCategoryCollection\Plugin\CatalogSearch\Model\Search\IndexBuilder" />
</type>
IndexBuilder.php
public function aroundBuild($subject, callable $proceed, RequestInterface $request)
{
try{
$select = $proceed($request);
$category = $this->registry->registry('current_category');//get current category
if(!is_null($category))
{
$categoryId = $category->getId();
$parentCategoryId = $category->getParentCategory()->getId();
if($categoryId == 6 || $parentCategoryId == 6)
{
$storeId = $this->storeManager->getStore()->getStoreId();
$rootCatId = $this->storeManager->getStore($storeId)->getRootCategoryId();
$productUniqueIds = $this->getCustomCollectionQuery();
$select->where('search_index.entity_id IN (' . join(',', $productUniqueIds) . ')');
}
}
return $select;
}catch(\Exception $e){
$this->logger->info($e->getMessage());
return $e->getMessage();
}
}
/**
*
* @return ProductIds[]
*/
public function getCustomCollectionQuery()
{
$websiteId = $this->storeManager->getStore()->getWebsiteId();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToSelect(array('entity_id','sku'));
$collection->addWebsiteFilter($websiteId);
$collection->setVisibility($this->_productVisibility->getVisibleInSiteIds());
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->setFlag('has_stock_status_filter', false)
->joinField('stock_item', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=1');
$getProductAllIds = $collection->getAllIds();
$getProductUniqueIds = array_unique($getProductAllIds);
return $getProductUniqueIds;
}