您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在WC 3.0+的单一产品页面中显示接近销售价格的折扣百分比

在WC 3.0+的单一产品页面中显示接近销售价格的折扣百分比

-2019 (避免四舍五入的价格问题) -2017 (避免NAN%百分比值)

在WooCommerce 3.0+中,该钩子已替换为另一个钩子,该钩子现在具有3个参数(但不再有该 参数)。

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)
    $_reg_price = floatval( strip_tags($regular_price) );
    $_sale_price = floatval( strip_tags($sale_price) );

    // Percentage calculation and text
    $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 ).'%';

这是功能相似的代码

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

这段代码会出现在您活动的子主题(或主题)的function.PHP文件中,也可能会出现在任何插件文件中。 该代码已经过测试并且可以工作。对于WooCommerce 3.0+版本。

其他 2022/1/1 18:14:21 有596人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶