Halloween Sale 15% off Ends in See the plans
PHP

"Only a Few Left" Low Stock Message

When a product with managed stock drops to a few units, shows a highlighted "Only 3 left, order soon" message instead of the plain stock count.

Don’t have WPIDE yet? Install it on your site

Code

add_filter( 'woocommerce_get_availability_text', function ( $text, $product ) {
    $threshold = 5; // Show the message at this many units or fewer.

    if ( ! $product instanceof WC_Product || ! $product->managing_stock() || ! $product->is_in_stock() ) {
        return $text;
    }

    $qty = (int) $product->get_stock_quantity();

    if ( $qty > 0 && $qty <= $threshold ) {
        return sprintf( 'Only %d left, order soon', $qty );
    }

    return $text;
}, 20, 2 );

add_filter( 'woocommerce_get_stock_html', function ( $html, $product ) {
    if ( $product instanceof WC_Product && $product->managing_stock() && $product->is_in_stock() && (int) $product->get_stock_quantity() <= 5 ) {
        $html = str_replace( 'class="stock ', 'style="color:#b32d2e;font-weight:600;" class="stock ', $html );
    }

    return $html;
}, 10, 2 );

Notes

Change $threshold to the quantity at which the message appears. Requires stock management on the product.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.