Displaying products with the “Out of stock” status after products in stock in the WooCommerce catalog

To display products with the "Out of stock" status after the products in stock on the product category page, you need to add a code to functions.php:

add_filter('posts_clauses', 'order_by_stock_status', 2000);


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

To display the "Out of stock" label in the product catalog, add the following code:

add_action('woocommerce_after_shop_loop_item_title', 'add_availability_in_catalog',8);

function add_availability_in_catalog()
{
    global $product;
    $availability = $product->get_availability();
    if ( ! empty( $availability['availability'] ) ) { ?>
        <span class="stock <?php echo esc_attr( $availability['class'] ); ?>"><?php echo wp_kses_post( $availability['availability'] ); ?></span>
    <?php }
}

Updated: 04.05.2020

Did this article help you? Rate it!
(No Ratings Yet)
Loading...

Support on Patreon https://www.patreon.com/processby

Leave a Reply

Your email address will not be published. Required fields are marked *

Contacts

E-mail: processby@gmail.com
Skype: inprocess.by
Belarus, Grodno

Send message