简体   繁体   中英

How to sort product collection on stock status in magento

I want to sort product collection on category page so that the in stock products shall appear before out of stock products. All the out of stock products will be displayed after the in stock products. I have already rewritten the Mage_Product_Block_List block.

You can use catalog_product_collection_load_before event.   
And in the observer:

public function modifyProductCollection(Varien_Event_Observer $observer) {
    //catalog_product_collection_load_before
    $collection = $observer->getCollection();

    $collection->getSelect()->joinLeft(
                array('_inventory_table' => $collection->getTable('cataloginventory/stock_item')),
                "_inventory_table.product_id = e.entity_id",
                array('is_in_stock')
            )
            ->order('is_in_stock DESC')
            ->order('created_at DESC');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM