WooCommerce Save Amount and Percent tags

You are here:
< All Topics

In order to show the amount or percent saved on a WooCommerce product that’s on Sale, you can make use of the custom code as below:

We recommend My Custom Functions plugin to add the code safely. Otherwise, you can add the code to functions.php of your child theme.

1. Show percentage (%) saved

Use {wc:save_percent} in the template and use the below code. For example

[if{wc:save_percent}][Save {wc:save_percent}%][{remove_line}], result Save 25.5%

/* PHP >= 5.6 */
add_filter(
	'wptelegram_pro_p2tg_post_data_wc:save_percent',
	function ( $value, $post ) {
		// If WooCommerce is active.
		if ( class_exists( 'woocommerce' ) && function_exists( 'wc_get_product' ) ) {
			// Get the product instance.
			$product = wc_get_product( $post->ID );
			// If we have an instance.
			if ( $product instanceof WC_Product ) {
				// Get the values.
				$sale_price    = $product->get_sale_price();
				$regular_price = $product->get_regular_price();
				// If there is sale price.
				if ( ! empty( $sale_price ) ) {
					// Number of decimal places to round the percent to.
					$decimal_points = 1;
					return round(
						( ( $regular_price - $sale_price ) / $regular_price ) * 100,
						$decimal_points
					);
				}
			}
		}
		// In all other cases.
		return $value;
	},
	10,
	2
);

2. Show amount ($) saved

Use {wc:save_amount} in the template and use the below code. For example

[if{wc:save_amount}][Save ${wc:save_amount}][{remove_line}], result Save $29

/* PHP >= 5.6 */
add_filter(
	'wptelegram_pro_p2tg_post_data_wc:save_amount',
	function ( $value, $post ) {
		// If WooCommerce is active.
		if ( class_exists( 'woocommerce' ) && function_exists( 'wc_get_product' ) ) {
			// Get the product instance.
			$product = wc_get_product( $post->ID );
			// If we have an instance.
			if ( $product instanceof WC_Product ) {
				// Get the values.
				$sale_price    = $product->get_sale_price();
				$regular_price = $product->get_regular_price();
				// If there is sale price.
				if ( ! empty( $sale_price ) ) {
					return $regular_price - $sale_price;
				}
			}
		}
		// In all other cases.
		return $value;
	},
	10,
	2
);
Previous Template conditional logic
Next WPML Post Language rules
Table of Contents

Ready to dive in? Buy NOW