Home Forums WoodMart support forum Sort products by “in stock first”

Sort products by “in stock first”

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #529634

    Golden1
    Participant

    I currently have my product archive to sort by “new” on default. I love that and want to keep it.

    I also would like out of stock products to be sent to the last page of the archive by default

    is that possible?

    #529866

    Hung Pham
    Keymaster

    Hi Golden1,

    Thanks for reaching to us.

    Add the below code to the functions.php file into the Child theme

    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;
    }

    Regards,

Viewing 2 posts - 1 through 2 (of 2 total)