December, 2015
Archive

By In Magento

Show ‘out of stock’ products as last

Customer behavior studies shows that customers check products on first page, if searched product is not there they will only small number will go to second page or third page. Most likely they will try to use search or redefine there search parameters to get better results. That is why is important to display on first page products that are ‘in stock’ and can be purchased right away.

Magento offer several options how to sort products on catalog page, with this little snippet we will extend that feature by keeping same order but ‘out of stock’ products will be displayed as last on catalog page.

There are many ways to do that however we will go for simplest one, by copying Magento files into our ‘local’ folder, or course same code can be wrapped up in form of module for more effective use. For example we want to use this feature only on ‘Sale’ category to effectively keep available products on top of list.

First step would be to copy file ‘Toolbar.php’ from Magento core folder to our local folder:
/app/code/local/Mage/Catalog/Block/Product/List/Toolbar.php

than open file in editor and find function ‘setCollection’ and copy complete code. We will rename new function from ‘setCollection’ to ‘setCatalogCollection’ and add code that will sort products by stock status. New function should look like this:

public function setCatalogCollection($collection)
{
$this->_collection = $collection;

$this->_collection->setCurPage($this->getCurrentPage());

// we need to set pagination only if passed value integer and more that 0
$limit = (int)$this->getLimit();
if ($limit) {
$this->_collection->setPageSize($limit);
}

if ($this->getCurrentOrder()) {
$this->_collection->joinField('inventory_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id','is_in_stock>=0', 'left')->setOrder('inventory_in_stock', 'desc');
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
}
return $this;
}

We will need to copy one more from Magento core folder to our local folder:
/app/code/local/Mage/Catalog/Block/Product/List.php

In ‘List.php’ file find line:
$toolbar->setCollection($collection);
and replace it with our new function:
$toolbar->setCatalogCollection($collection);

Save all changes, refresh cache and check front end to see how code works. If everything is done properly your catalog page ordering will be adjusted and ‘out of stock’ products will be listed as last in collection.

It is important not to overwrite Magento default function ‘setCollection’ since it might happen that some 3rd party modules will use it and can cause site to crash (issue confirmed with free blog extensions).

I hope that this little trick with help you, if I have some free time in next few weeks I will try to create module to save you time and spare you from editing files.

Read more