3

Below script shows out of stock products in only one category with Display Out Of Stock option yes in the admin by using helper file.

Here is the code:

<?php

namespace Vendor\Module\Helper\Catalog;

class Stock extends \Magento\CatalogInventory\Helper\Stock
{    
    public function addIsInStockFilterToCollection($collection)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $category = $objectManager->get('Magento\Framework\Registry')
                                  ->registry('current_category');//get current category

        if(!is_null($category))
        {

            $categoryId = $category->getId(); //current category id
            $stockFlag = 'has_stock_status_filter';

            if (!$collection->hasFlag($stockFlag)) 
            {
                $isShowOutOfStock = $this->scopeConfig->getValue(
                    \Magento\CatalogInventory\Model\Configuration::XML_PATH_SHOW_OUT_OF_STOCK,
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                );
                $resource = $this->getStockStatusResource();

                //100 static category Id 
                if($categoryId == 100)
                {
                   //show display out of stock products for particular category
                   $resource->addStockDataToCollection(
                        $collection,
                        false
                    );
                }
                else
                {
                    $resource->addStockDataToCollection(
                        $collection,
                        $isShowOutOfStock
                    );
                }
                $collection->setFlag($stockFlag, true); 
            }
        }
       }
}

?>

My problem is:

It's working only for category page and the out of stock products coming into the search result page.

I want to show out of stock products for only one category page should hide in all other categories. But the Out of stock products that belong only to the Category Id '100' should show in the search result page.

Please can you help me to fix this issue?

  • hi, got any solution? – Manjunath Feb 6 at 15:08
  • 1
    Got confused here, you want to show OOS product on listing page or search result page? – Ashish Ranade Feb 17 at 7:40
  • @AshishRanade, Yes only for specific category, the category id is 100, also in search result page all products which belongs to category id 100 – Manjunath Feb 18 at 9:24
  • Do you also want to sell those products? Or just display as OOS item? – Arif Ahmad Feb 20 at 14:05
  • Do you want to display it on any pages? is it okay to display in view file? – sarvesh Dineshkumar Patel Feb 21 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.