Skip to main content
nimblehelp Let's chat

Nimble Blog

How to show the actual percentage discount in the Woocommerce SALE label

Author

Lukas Cech

Published

November 14, 2023

Category

Useful info, Webdesign

I always found the Woocommerce “SALE” label not very useful – it’s already obvious from the reduced price that the item is on sale. How about making it more helpful to the visitor by showing the actual percentage of the discount? Here’s a function that does it for you.

Now you can 🙂 Here’s a function that needs to go into your functions.php:

//Calculate and show percentage of discount instead of the SALE label - by www.Nimble.help

function custom_sale_flash($html, $post, $product) {
    // Check if the product is on sale
    if ($product->is_on_sale()) {
        // Get regular and sale prices
        $regular_price = (float) $product->get_regular_price();
        $sale_price = (float) $product->get_sale_price();

        // Calculate the percentage discount
        $percentage = round((($regular_price - $sale_price) / $regular_price) * 100);

        // Return the custom sale flash HTML
        return '<span class="onsale">-' . $percentage . '%</span>';
    }

    // Return default sale flash if not on sale
    return $html;
}

add_filter('woocommerce_sale_flash', 'custom_sale_flash', 10, 3);

What does this function do?

It calculates the percentage difference between the sale price and the regular price of every product.

  1. The function hooks into woocommerce_sale_flash, which is responsible for displaying the SALE! label.
  2. Check for Sale: It first checks if the product is actually on sale.
  3. Calculate Discount Percentage: If the product is on sale, the function calculates the percentage discount based on the regular price and the sale price.
  4. Custom Sale Flash HTML: It then returns a custom HTML span element displaying the discount percentage.
  5. Default Sale Flash: If the product is not on sale, the default sale flash is returned.

This function will dynamically replace the usual sale flash text with the actual percentage discount for each product on sale in your WooCommerce product archive pages. Ensure to clear your site’s cache (if you’re using a caching plugin) to see the changes reflected immediately.

The appearance of the sale flash can be further styled with CSS to match your site’s design.