The post_clauses filter in WooCommerce allows you to modify the SQL clauses that are used to retrieve products from the database. You can use this filter to sort products by popularity and stock status in the WooCommerce catalog by adding the following code to your theme’s functions.php file or a custom plugin:

<?php

/**
 * Order product collections by stock status, instock products first.
 */
class iWC_Orderby_Stock_Status
{

    public function __construct()
    {
        // Check if WooCommerce is active
        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
            add_filter('posts_clauses', array($this, 'order_by_stock_status'), 2000);
        }
    }

    public function order_by_stock_status($posts_clauses)
    {
        global $wpdb;
        // only change query on WooCommerce loops
        if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag())) {
            $posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
            $posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
            $posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
        }
        return $posts_clauses;
    }
}

new iWC_Orderby_Stock_Status;

?>

This code will sort products out-of-stock products to the bottom of the catalog.
Keep in mind that this code will only affect the sorting of products in the WooCommerce catalog. If you want to sort products in other areas of your website, such as on the homepage or in the search results, you may need to make additional changes.

Leave a Reply

Your email address will not be published.