I am trying to add save amount total on the sale flash badge using this snippet here below but there is something wrong since it is not working.
Any advice would be really appreciated.
// Add save amount on the sale badge.
add_filter( 'woocommerce_sale_flash', 'woocommerce_custom_badge', 10, 2 );
function woocommerce_custom_badge( $price, $product ) {
$saved = wc_price( $product->regular_price - $product->sale_price );
return $price . sprintf( __(' <div class="savings">Save %s</div>', 'woocommerce' ), $saved );
}
Thanks
Added WC 3+ compatibility
You don't have the correct arguments in your filter ($price
doesn't exist for example), see here the related source code for woocommerce_sale_flash
filter hook to understand better:
/*
* The filter hook woocommerce_sale_flash is located in:
* templates/loop/sale-flash.php and templates/single-product/sale-flash.php
*/
<?php if ( $product->is_on_sale() ) : ?>
<?php echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale">' . esc_html__( 'Sale!', 'woocommerce' ) . '</span>', $post, $product ); ?>
So your working code is going to be something like:
add_filter( 'woocommerce_sale_flash', 'woocommerce_custom_badge', 10, 3 );
function woocommerce_custom_badge( $output_html, $post, $product ) {
// Added compatibility with WC +3
$regular_price = method_exists( $product, 'get_regular_price' ) ? $product->get_regular_price() : $product->regular_price;
$sale_price = method_exists( $product, 'get_sale_price' ) ? $product->get_sale_price() : $product->sale_price;
$saved_price = wc_price( $regular_price - $sale_price );
$output_html = '<span class="onsale">' . esc_html__( 'Save', 'woocommerce' ) . ' ' . $saved_price . '</span>';
return $output_html;
}
The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.