Display the discounted percentage near sale price in Single product pages for WC 3.0+

那年仲夏 提交于 2019-11-27 02:10:21

woocommerce_sale_price_html hook has been replaced by a different hook in WooCommerce 3.0+, that has now 3 arguments (but not the $product argument anymore).

Here is that functional similar code:

// Only for WooCommerce version 3.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;
}

This 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 only for WooCommerce version 3.0+


Update to avoid NAN% percentage value when regular and sale prices are html pre-formatted:

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>';
}

This 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 only for WooCommerce version 3.0+ (thanks to @AsifRao)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!