I have already tried the method mentioned here on SO and other forums but it is not working. I am using Magento ver. 1.7.0.2 and I would like to move all the Out of Stock products to the end of the product list and search result page.
Here is what I tried:
I made a copy of Collection.php from /app/code/core/Mage/Catalog/Model/Resource/Product/
to /app/code/local/Mage/Catalog/Model/Resource/Product/
and pasted below code at the begining of addAttributeToSort function.
$this->getSelect()->joinLeft(array('_inventory_table' => $this->getTable('cataloginventory/stock_status')), '_inventory_table.product_id = e.entity_id', array('stock_status'));
$this->getSelect()->order('stock_status DESC');
it didn't work though and I prefer an option that can be done via the magento theme instead of editing core files and copying it over to local directory. How can I do this?
I would be looking to implement a more direct approach in the list.phtml file or with a function in the corresponding class file eg Yourpackage/Yourmodule/Block/Product/List.php.
You can access stock levels of each $_product
using this code
$cabac_stockObject = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
//get the stock levels
$cabac_stockQuantityAvailable = (int)$cabac_stockObject->getQty() - (int)$cabac_stockObject->getMinimumQty(); //returns string! Like 10.000 or 0.0000 for 10 or 0 so cast to (int)
$cabac_stockStatus = (int)$cabac_stockObject->getIsInStock(); //returns string! Like 10.000 or 0.0000 for 10 or 0 so cast to (int)
And then maybe loop over the collection, add the product object and stock count into an array, sort by stock count and then pass the sorted array into your list.phtml
's foreach
loop.
So something like this (apologies for rough pseudo code)
foreach ($_productCollection as $_product){
$cabac_stockObject = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
//get the stock levels
$cabac_stockQuantityAvailable = (int)$cabac_stockObject->getQty() - (int)$cabac_stockObject->getMinimumQty();
$cabac_stockStatus = (int)$cabac_stockObject->getIsInStock();
if($cabac_stockQuantityAvailable==0 || $cabac_stockStatus==0 ){
$cabac_stockQuantityAvailable = 0;
}
//store the stock quantity and $_product in an array
}
//sort the array as you see fit
//foreach ($sortedArray['products'] as $_product){
//display the products
//}