phpwordpresswoocommerceproduct

Show Out of stock products at the end in Woocommerce


Is it possible to show out of stock products at the end of a category or page in wordpress?

So the customer first see the products that are available and after that the products that are out of stock.


Solution

  • This is the same as Viktor & Bogdan's answer, but without the extra Class code.

    It uses the post_clause filter to modify the product query. We JOIN the wp_postmeta table to the query and prepend an orderby _stock_status clause to the existing query. This way any other orderby clauses remain in the query as well.

    add_filter('posts_clauses', 'order_by_stock_status');
    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() || is_product_taxonomy())) {
            $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;
    }
    

    You could change istockstatus.meta_value ASC to istockstatus.meta_value DESC if you for some reason wanted the Out Of Stock items first.

    Tested on WP: 4.8; WC 3.0.8