Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

woocommerce sort products by in stock and out of stock in front-end

I want to show in stock products first in products category or if possible in any where and then I want to display out of stock products too after them in Woocommerce

Actually there are many products which have not quantity number but those are in stock, So it is need to check in stock status, But I prefer to have more quantities first

How can I make a force for current sorting in such case? Thank you very much

like image 244
Farhad Sakhaei Avatar asked Mar 10 '23 17:03

Farhad Sakhaei


1 Answers

Using this code:

<?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, 2);
        }
    }

    public function order_by_stock_status($posts_clauses, $wp_query)
    {
        global $wpdb;
        // only change query on WooCommerce loops
        if (false === is_admin() && $wp_query->is_post_type_archive('product')) {
            $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;

?>
like image 97
Farhad Sakhaei Avatar answered Apr 07 '23 01:04

Farhad Sakhaei