根据 Woocommerce 会话数据添加自定义百分比费用

Add a custom percentage fee based on Woocommerce session data

下面的代码将向 woocommerce 结帐表单添加一个单选按钮。 如果买家选择单选按钮,将向购物车添加固定数量的钱,如 20 美元 $fee = 20;。我需要的不是像 3% 那样添加固定金额来添加总额的 %。我需要做的改变是在这部分代码中:

add_action( 'woocommerce_cart_calculate_fees', 'custom_checkout_radio_choice_fee', 20, 1 );
function custom_checkout_radio_choice_fee( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    $radio = WC()->session->get( 'radio_chosen' );
    $disc=$order->get_total();

    if ( "option_1" == $radio ) {
        $fee = 20;
    } elseif ( "option_2" == $radio ) {
        $fee = 30;
    }

    $cart->add_fee( __('Option Fee', 'woocommerce'), $fee );
}

如果用户单击单选按钮前的总金额为 200 美元,则单击单选按钮后总金额变为 206 美元(添加 3%)。

$disc=$order->get_total() * 1.03;

这将使你的总计+(总计*3%)

未定义 $order 变量,在下订单之前 WC_Order 对象不存在。请尝试以下操作:

add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_radio_button_choice', 10, 1 );
function custom_fee_based_on_radio_button_choice( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    $radio = WC()->session->get( 'radio_chosen' );

    if ( "option_1" == $radio ) {
        $percent = 20;
    } elseif ( "option_2" == $radio ) {
        $percent = 30;
    }

    if( isset($percent) ) {
        $fee = $cart->get_subtotal() * $percent / 100; // Calculation
        $cart->add_fee( __('Option Fee', 'woocommerce'). " ($percent%)", $fee );    
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。