Updated - 2019 (avoid rounding price issue) - 2017 (avoid NAN%
percentage value)
The hook haswoocommerce_sale_price_html
been replaced by another hook in WooCommerce 3. 0+, which now has 3 arguments (but no longer an argument $product
).
add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );
function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
$_reg_price = floatval( strip_tags($regular_price) );
$_sale_price = floatval( strip_tags($sale_price) );
$percentage = round( ( $_reg_price - $_sale_price ) / $_reg_price * 100 ).'%';
$percentage_txt = ' ' . __(' Save ', 'woocommerce' ) . $percentage;
$formatted_regular_price = is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price;
$formatted_sale_price = is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price;
echo '<del>' . $formatted_regular_price . '</del> <ins>' . $formatted_sale_price . $percentage_txt . '</ins>';
}
function.php ( ), .
. WooCommerce 3. 0+ ( @Mikebcn @AsifRao)
round()
, number_format()
number_format_i18n()
:
$percentage = number_format_i18n( ( $_reg_price - $_sale_price ) / $_reg_price * 100, 0 ).'%';
$percentage = number_format( ( $_reg_price - $_sale_price ) / $_reg_price * 100, 0 ).'%';
: :
add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );
function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
$percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
$percentage_txt = ' ' . __(' Save ', 'woocommerce' ) . $percentage;
$price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) . $percentage_txt : $sale_price . $percentage_txt ) . '</ins>';
return $price;
}
function.php ( ), .
. WooCommerce 3. 0+.