WooCommerce PHP Beginner Requires WooCommerce

Show the Discount Percentage on Sale Badges

Replace the plain "Sale!" badge with how much the customer saves, like "-25%", calculated from each product's prices.

Tested on WordPress 7.1 PHP 8.3 Updated
functions.php 20 lines
add_filter( 'woocommerce_sale_flash', function ( string $html, $post, WC_Product $product ): string {
	if ( $product->is_type( 'variable' ) ) {
		// Use the biggest saving across variations.
		$percent = 0;
		foreach ( $product->get_children() as $child_id ) {
			$child = wc_get_product( $child_id );
			if ( $child && $child->is_on_sale() && (float) $child->get_regular_price() > 0 ) {
				$percent = max( $percent, 100 - ( (float) $child->get_sale_price() / (float) $child->get_regular_price() * 100 ) );
			}
		}
	} else {
		$regular = (float) $product->get_regular_price();
		$percent = $regular > 0 ? 100 - ( (float) $product->get_sale_price() / $regular * 100 ) : 0;
	}

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

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

“Sale!” tells shoppers something is cheaper, but not by how much. A percentage is more persuasive and easier to compare. This snippet calculates it for every product on sale.

How it works

WooCommerce prints the sale badge through the woocommerce_sale_flash filter. For simple products the snippet compares the sale price with the regular price. For variable products it checks each variation on sale and shows the biggest saving, which is what “up to” sales usually advertise.

The badge keeps WooCommerce’s onsale class, so your theme’s existing badge styling still applies.

Things to watch

  • Grouped and external products fall back to the normal badge if no percentage can be worked out.
  • Block themes using the Product Sale Badge block don’t use this filter.
  • On stores with many large variable products, this adds a little work to each product card. Cache your shop pages.

How to test it

Put a product on sale, for example from 40 to 30, and open the shop. The badge should say “-25%”.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only