wordpresswoocommerceproductstock

Woocommerce product custom displayed stock status based on stock quantity


I want to show the actual stock quantity when the quantity is under 20 and a text like "more than 20" when the quantity is more han 20 for products with or without variations. Also for products that only have the stock status set to "in stock" (without quantity) i want the text "more than 20" to show. I have tried some different options but can't get it right.

In short what i need to achieve: When stock is 20 or less: show actual stock When stock is more than 20: show "more than 20" When stockstatus is set to in stock: show "more than 20"

Would be happy for some advices here.

I tried to change the code below in different ways, as it is now, it just shows "more than 20" and "less than 20" and products that are just in stock without quantity get "out of stock" message:

add_filter('woocommerce_get_stock_html', function($html, $product) {
    $current_stock = $product->get_stock_quantity();
    if ($current_stock <= 0) {
        $new_html = __('Out of stock', 'txtdomain');
    } else if ($current_stock > 20) {
        $new_html = sprintf('More than 20 %s', __('in stock', 'txtdomain'));
    } else if ($current_stock < 19) {
        $new_html = sprintf('Less than 20 %s', __('in stock', 'txtdomain'));
    } else {
        $new_html = __('In stock', 'txtdomain');
    }
    return sprintf('<p class="stock">%s</p>', $new_html);
}, 10, 2);

Also this topic seems to be very close to the solution, but it did not show any quantity when i tried: Woocommerce variable product stock qty message


Solution

  • Try the following revisited code using get_manage_stock() method to solve your issue:

    add_filter('woocommerce_get_stock_html', 'filter_wc_get_stock_html', 10, 2 );
    function filter_wc_get_stock_html($html, $product) {
        $current_stock = $product->get_stock_quantity();
        $manage_stock  = $product->get_manage_stock();
        $stock_status  = $product->get_stock_status();
    
        if ( $manage_stock ) {
            if ( $current_stock <= 0 ) {
            $new_html = __('Out of stock', 'txtdomain');
            } elseif ($current_stock < 20) {
                $new_html = sprintf('Less than 20 %s', __('in stock', 'txtdomain'));
            } elseif ($current_stock > 19) {
                $new_html = sprintf('Up to 20 %s', __('in stock', 'txtdomain'));
            }
        } else {
            if ( $stock_status === 'outofstock' ) {
                $new_html = __('Out of stock', 'txtdomain');
            } else {
                $new_html = __('In stock', 'txtdomain');
            }
        }
        return sprintf('<p class="stock">%s</p>', $new_html);
    }
    

    It should work.