"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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.