Friday 20 January 2012

Magento 1.5: Keep out of stock product always at last in the product listing page

Not a good habit  of changing in the core files, first keep in side local folder if any changes required in core files.
You will get less pain during magento version up gradation.

Below code will help you to keep out of stock products in magento always at  last in the product listing page .

First copy Collection.php file from /app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product/Collection.php  to /app/code/local/Mage/Catalog/Model/Resource/Eav/Mysql4/Product/Collection.php folder structure .

Put below code:

$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');

Beginning of the function addAttributeToSort(). See below how it will look like


 public function addAttributeToSort($attribute, $dir='asc') {

 
    $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');


Now you are done.

Good luck

7 comments:

  1. How can we sort by more parameters, for example, I need to sort by two parameters, first by "news_from_date" and second by "stock_status", because even the out of stock products are displayed last, the newest products need to be displayed first, always, and we can not discard this priority of sorting.

    Thanks.

    ReplyDelete
  2. It worked fine for several attributes, like "created_at", "position" and others, however when I click to sort by price, I got this error:

    "You cannot define a correlation name '_inventory_table' more than once"

    Do you know about why did I get it? Your code was the only one that really worked fine on 1.7.0.2, but we need to fix this error and make your tip being 100% amazing.

    ReplyDelete
  3. Hello João,

    I have implemented this code in magento 1.5 and working perfectly. I have to look into this issue for 1.7. I just google your problem and found same issue with other developer and solution for the same.

    http://www.magentocommerce.com/boards/viewthread/74582/P30/
    You may try the same.

    In mean while am also trying to fix this issue for 1.7

    Regards
    Ajit


    ReplyDelete