php - How to sort WooCommerce products page by latest in-stock items first?

admin2025-01-07  3

How to sort the WooCommerce products page by latest in-stock items first and all the out-of-stock items to the last?

Currently, I'm using a code snippet from "/" and it will sort the products which are in stock first and all the out-of-stock items last. But the problem is the products are not in the latest order. It shows old in-stock products first.

How to sort the WooCommerce products page by latest in-stock items first and all the out-of-stock items to the last?

Currently, I'm using a code snippet from "https://www.businessbloomer.com/woocommerce-show-in-stock-products-first-shop/" and it will sort the products which are in stock first and all the out-of-stock items last. But the problem is the products are not in the latest order. It shows old in-stock products first.

Share Improve this question edited Apr 14, 2022 at 3:28 WPswvim asked Apr 13, 2022 at 9:23 WPswvimWPswvim 13 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

There are several options.

  1. If you want to show out of stock but in latest positions you can combine your code snippet with lastest inventary order. You dont need code for this, in customizer theme usually you can change this option:

  1. If you want to hide out of stock and show in stock by latest. Then deleted your snippet, use same option that 1 and add this option too:

Woocommerce -> Products -> Inventary -> Hide out of stock products.

It is the best option for most stores, because it hides the products from the listings, but does not hide product page, and this does not affect seo or require additional work.

there's also additional config to hide in serach results like explain here

Many things that a few years ago had to be done with code, Woocommrece brings that option added.

Or You can use this free plugin: WooCommerce Sort By Stock

Regards

I had the same problem. Most of the time, when issue is clearly stated AI can give you a fast answer. The modified code is below:

/**
 * @snippet       Sort Products By Stock Status and Date - WooCommerce Shop
 * @how-to        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @compatible    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'woocommerce_get_catalog_ordering_args', 'bbloomer_first_sort_by_stock_and_date', 9999 );

function bbloomer_first_sort_by_stock_and_date( $args ) {
    // Order by stock status first
    $args['orderby'] = array(
        'meta_value' => 'ASC', // In-stock products first
        'date'       => 'DESC' // Latest products first
    );
    $args['meta_key'] = '_stock_status';
    return $args;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736264228a951.html

最新回复(0)