Stock Level Progress Bar on Product Pages
Shows a bar with how much of a product's stock is left, such as "Hurry, only 4 left", when stock is running low, to create honest urgency.
Opens WPIDE on
Code
$wpide_stock_bar = array(
'show_below' => 15, // Show the bar at or below this stock level.
'full_at' => 30, // Stock level that counts as a full bar.
);
add_action( 'woocommerce_single_product_summary', function () use ( $wpide_stock_bar ) {
global $product;
if ( ! $product instanceof WC_Product || ! $product->managing_stock() || ! $product->is_in_stock() ) {
return;
}
$stock = (int) $product->get_stock_quantity();
if ( $stock < 1 || $stock > $wpide_stock_bar['show_below'] ) {
return;
}
$percent = max( 5, min( 100, round( $stock / $wpide_stock_bar['full_at'] * 100 ) ) );
printf(
'<div class="wpide-stock-bar"><p>%1$s</p><div role="progressbar" aria-valuemin="0" aria-valuemax="%2$d" aria-valuenow="%3$d" aria-label="%4$s" style="height:8px;background:#eee;border-radius:4px;overflow:hidden"><span style="display:block;height:100%%;width:%5$d%%;background:%6$s;transition:width .6s ease"></span></div></div><style>@media (prefers-reduced-motion:reduce){.wpide-stock-bar span{transition:none!important}}</style>',
esc_html( sprintf( _n( 'Hurry, only %d left in stock', 'Hurry, only %d left in stock', $stock ), $stock ) ),
(int) $wpide_stock_bar['full_at'],
(int) $stock,
esc_attr( 'Stock remaining' ),
(int) $percent,
esc_attr( $percent < 30 ? '#d63638' : '#dba617' )
);
}, 26 );
Notes
Shown only for stock-managed products at or below 'show_below' units, and the animation respects reduced-motion settings.
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.