Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.