我在
wc-settings&tab=general
下使用 0 位小数,这对于我的用例来说效果很好。但现在为特定付款方式添加折扣,目前设置为 10%。
对于 12 美元的商品,它会将折扣值四舍五入为 1 - 由于前面提到的 0 位小数设置,总计为 11,而不是 10.8。
我想出的最接近的是以下过滤器,但导致运费也从 23 美元升至 23.23 美元。知道如何仅将 2 位小数应用于折扣金额而不干扰其他地方吗?
// Change woo settings from 0 at the moment in backend to 2 decimals for wallet payment
add_filter( 'wc_get_price_decimals', 'custom_price_decimals_for_wallet_s0dgPHq2',10,1);
function custom_price_decimals_for_wallet_s0dgPHq2( $decimals ) {
// Check if we are on the front-end and WooCommerce session is available
if ( !is_admin() && WC()->session && isset(WC()->session->chosen_payment_method) ) {
// Only change decimal places if the chosen payment method is wallet
if ( WC()->session->chosen_payment_method === 'wallet' ) {
// Set to 2 decimals for wallet payments
$decimals = 2;
return $decimals;
}
// Return the default value for other cases
return $decimals;
}
}
这也是我的折扣码
add_filter( 'woocommerce_cart_calculate_fees', 'discount_based_on_payment_method_e643e', 10, 1 );
function discount_based_on_payment_method_e643e( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return;
$targeted_payment_method = 'wallet'; // Here define the desired payment method
global $abc_options;
$wallet_pay_discount_amount = $abc_options['wallet_payment_discount_amount_value'];
$wallet_pay_discount_amount_formated = $wallet_pay_discount_amount / 100; // results in 0.10 for 10% and so on
if( WC()->session->get('chosen_payment_method') === $targeted_payment_method ) {
$cart_subtotal = WC()->cart->get_subtotal();
$discount = $cart_subtotal * $wallet_pay_discount_amount_formated;
$fee_description = '~ ' . $wallet_pay_discount_amount . '% ' . __('Discount Wallet Payment', 'nm-ffk');
$cart->add_fee($fee_description, -$discount);
}
}
要仅更改 WooCommerce 结帐页面中显示的费用金额小数位,请使用以下代码替换:
add_filter( 'woocommerce_cart_totals_fee_html', 'filter_woo_cart_totals_fee_html', 10, 2 );
function filter_woo_cart_totals_fee_html( $fee_html, $fee ){
$args = array('decimals' => 2 );
return WC()->cart->display_prices_including_tax() ? wc_price( $fee->total + $fee->tax, $args ) : wc_price( $fee->total, $args );
}
add_filter( 'woocommerce_cart_calculate_fees', 'discount_based_on_payment_method_e643e', 10, 1 );
function discount_based_on_payment_method_e643e( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return;
$payment_id = 'wallet'; // The targeted payment method ID
if( WC()->session->get('chosen_payment_method') === $payment_id ) {
global $abc_options;
$discount_rate = $abc_options['wallet_payment_discount_amount_value'];
$discount_amount = WC()->cart->get_subtotal() * $discount_rate / 100;
$fee_description = '~ ' . $discount_rate . '% ' . __('Discount Wallet Payment', 'nm-ffk');
$cart->add_fee($fee_description, -$discount_amount);
}
}