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 a bit more code that will hook into the right part of the WooCommerce page and replace the default sale price with our new sale price, including the percentage saved.

  3. Add the following code to the bottom of your file:
    // Add percentage saved next to sale price 
    add_filter( 'woocommerce_sale_price_html', 'woocommerce_cookbook_percentage_saved', 10, 2 ); 
    function woocommerce_cookbook_percentage_saved( $price, $product ) { 
        $percentage_saved = woocommerce_cookbook_calculate_percentage_saved( $product ); 
        return $price . sprintf( __( ' Save %s', 'woocommerce' ), $percentage_saved . '%' ); 
    }
  4. Save the file and upload it to your site.
  5. You should now see the percentage saved where the sale price used to be.
    How to do it…

There's more…

This recipe and the previous one both changed how the sale price was displayed. As you can see, they can be done in very different ways. A developer could combine these methods and get the best from both worlds. If you're looking to get started with customizing your WooCommerce site but don't know where to start, a good place would be the WooCommerce templates located in the /templates/ folder in the WooCommerce plugin. You can see all of the hooks used to display various pieces of functionality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset