Book Image

WooCommerce Cookbook

By : Patrick Rauland
Book Image

WooCommerce Cookbook

By: Patrick Rauland

Overview of this book

Table of Contents (17 chapters)
WooCommerce Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Displaying the amount saved as a percentage


With higher ticket items, it's sometimes nice to show the customer the percentage saved versus the dollar amount. With two pieces of code, we can change this functionality.

Getting ready

Make sure you have a product in your store that's on sale.

How to do it…

Currently, the only way to do display the amount saved in a percentage is with a bit of custom code. You have to add the percentage saved to the HTML. This can be done with two small snippets.

  1. In your code editor, open up your theme's functions.php file, located under wp-content/themes/your-theme-name/, or your custom WooCommerce plugin.

  2. Add the following code to the bottom of that file:

    // calculate the percentage saved. 
    function woocommerce_cookbook_calculate_percentage_saved( $product ) { 
        return round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product- >get_regular_price() ) * 100 ); 
    }

    This piece of code calculates the percentage saved. Now we need to write...