I want to show the discount sale percentage under the prices (regular and sale prices).
There is a very close solution to that in the post:
Display the discounted percentage near sale price in Single product pages for WC 3.0+
But the problem is that it changes the price. Before the code appears like this:
And after the code like this:
As you can see the decimals disappeared and the percentage is not correct as it should show 15% Price 55€-15% off --> 46,75€
The code used:
add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );
function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
// Getting the clean numeric prices (without html and currency)
$regular_price = floatval( strip_tags($regular_price) );
$sale_price = floatval( strip_tags($sale_price) );
// Percentage calculation and text
$percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
$percentage_txt = __(' Save ', 'woocommerce' ).$percentage;
return '<del>' . wc_price( $regular_price ) . '</del> <ins>' . wc_price( $sale_price ) . $percentage_txt . '</ins>';
}
My expected result would be something like this, but can't find the way to do it.
I've been reading a lot of posts about it but couldn't find the right solution. My apologies if I duplicate the post. Thank you
Update 08/24/2019 Solved
I finally solved the problem and got the result as i wanted after some research in toher websites. I leave here the code i used so anyone can use it too.
add_action( 'woocommerce_single_product_summary',
'porcentaje_ahorro_ficha_producto', 12 );
function porcentaje_ahorro_ficha_producto() {
global $product;
if ( ! $product->is_on_sale() ) return;
if ( $product->is_type( 'simple' ) ) {
$max_percentage = ( ( $product->get_regular_price() - $product-
>get_sale_price() ) / $product->get_regular_price() ) * 100;
} elseif ( $product->is_type( 'variable' ) ) {
$max_percentage = 0;
foreach ( $product->get_children() as $child_id ) {
$variation = wc_get_product( $child_id );
$price = $variation->get_regular_price();
$sale = $variation->get_sale_price();
if ( $price != 0 && ! empty( $sale ) ) {
$percentage = ( $price - $sale ) / $price * 100;
}
if ( $percentage > $max_percentage ) {
$max_percentage = $percentage;
}
}
}
if ( $max_percentage > 0 ) echo "<div class='porcentaje-ahorro'>-" .
round($max_percentage) . "%</div>";
}
Then I did some css and that's all. thank you all for your support.