WooCommerce: Display Discounts on Single Product Pages

In WooCommerce, showing the sale percentage under the price on single product pages can help customers quickly identify discounts and make informed purchase decisions. In this tutorial, we’ll learn how to implement this feature using a custom function.

/**
* Snippet Name:  Display sale percentage under price
* Snippet Author:  wpsnippets.dev
*/

// Define a function to display sale percentage under the price on single product pages
function display_sale_percentage() {
    global $product;
    
    if ($product->is_on_sale()) {    // Check if the product is on sale
        // Get regular and sale prices
        $regular_price = $product->get_regular_price();
        $sale_price = $product->get_sale_price();
        $percentage = round(100 - ($sale_price / $regular_price * 100));  // Calculate and display the sale percentage
        ?>
        <div class="sale-percentage">
            <?php echo esc_html($percentage) . '% ' . __('off', 'textdomain'); ?>
        </div>
        <?php
    }
}
add_action('woocommerce_single_product_summary', 'display_sale_percentage', 11);

Code Explanation

  • The display_sale_percentage function shows the sale percentage beneath the price on single product pages in WooCommerce. It calculates the sale percentage based on the regular and sale prices of the product. If the product is on sale, it displays the percentage discount under the price on single product pages.
  • The add_action function connects display_sale_percentage to the woocommerce_single_product_summary action, ensuring it appears after default product summary elements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top