# Show the Discount Percentage on Sale Badges

> Replaces the "Sale!" badge with the actual discount, for example "-25%". Variable products show the largest discount among their variations.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, sale, badges, pricing
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-sale-badge-percentage/

## Code

```php
add_filter( 'woocommerce_sale_flash', function ( $html, $post, $product ) {
    if ( ! $product instanceof WC_Product ) {
        return $html;
    }

    $percent = 0;

    if ( $product->is_type( 'variable' ) ) {
        foreach ( $product->get_children() as $child_id ) {
            $child = wc_get_product( $child_id );

            if ( ! $child || ! $child->is_on_sale() ) {
                continue;
            }

            $regular = (float) $child->get_regular_price();
            $sale    = (float) $child->get_sale_price();

            if ( $regular > 0 ) {
                $percent = max( $percent, ( $regular - $sale ) / $regular * 100 );
            }
        }
    } else {
        $regular = (float) $product->get_regular_price();
        $sale    = (float) $product->get_sale_price();

        if ( $regular > 0 && '' !== $product->get_sale_price() ) {
            $percent = ( $regular - $sale ) / $regular * 100;
        }
    }

    if ( $percent < 1 ) {
        return $html;
    }

    return '<span class="onsale">-' . esc_html( (string) (int) round( $percent ) ) . '%</span>';
}, 10, 3 );
```

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Show the Discount Percentage on Sale Badges" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
