Magento – Hide out of stock products

categorycollection;magento-1.9product-collection

I want to hide out of stock products from showing in search or category pages and I do not want to use the built in feature:

Admin >> System >> Configuration >> Catalog >> Inventory >> Stock Options
Display Out of Stock product -> No

The reason is that I use and sort out of stock products and if I disable them completely I can't filter by Stock status.

How do I put a filter on the category and search collection?

Best Answer

I have done it and I know it will help a lot of people so this is what I did to achieve this:

Firstly you need to modify the collection which is loaded in:

app\code\core\Mage\Catalog\Block\Product\List.php

You're best making a local copy and editing that:

app\code\local\Mage\Catalog\Block\Product\List.php

Find this line:

$this->_productCollection = $layer->getProductCollection();

Directly under it place this code:

$in_Collection = Mage::getModel('cataloginventory/stock_item')
            ->getCollection()
            ->addFieldToFilter('is_in_stock',1);

$in_Products = array();
foreach($in_Collection as $_collection) {
        $in_Products[] = $_collection->getProductId();
}

$this->_productCollection->addAttributeToSelect('*')
                         ->addAttributeToFilter('entity_id', array('in'=>$in_Products));

I hope this helps :)

Related Topic