Alex
Alex

Reputation: 537

How can I change woocommerce_sale_flash from Text to Discount Percentage

I would like to know what would be the code to change woocommerce_sale_flash from the default text which is "Sale!" to the Discount Percentage you actually are saving.

Just now I have this piece of code which changes the text of the sale flash icon:

add_filter('woocommerce_sale_flash', 'my_custom_sale_flash');
function my_custom_sale_flash($text, $post, $_product) {
return '<span class="onsale"> Discount!</span>';  
}

Instead of displaying the same text each time, it should display the actual discount (for example: 25% off) of the product.

Upvotes: 1

Views: 7349

Answers (1)

Rohil_PHPBeginner
Rohil_PHPBeginner

Reputation: 6080

Try out this :

add_filter('woocommerce_sale_flash', 'my_custom_sale_flash');
function my_custom_sale_flash($text) {
    global $product;
    $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
    return '<span class="onsale">'.$percentage.'%</span>';  
}       

Upvotes: 9

Related Questions