1

在应用折扣后,我正在尝试根据小计向我的 woocommerce 购物车添加费用:

    add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;

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

    $percentage = 0.01;
    $surcharge =  $woocommerce->cart->subtotal - $woocommerce->cart->get_cart_discount_total(); 
    $woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );

}

我不相信$woocommerce->cart->get_cart_discount_total()可以在动作挂钩中使用类似的调用,这就是我不断0.00收取费用的原因。

我还阅读了一些不推荐使用的 WC 值并且将始终显示为零,但它没有解释为什么这些数量出现在过滤器中而不是操作中。

我还可以在操作中使用什么来获得相同的数字并添加百分比费用?

4

2 回答 2

1

WC_Cart对象参数包含在动作woocommerce_cart_calculate_fees钩子中。我还使用百分比金额计算,因为我想您只是在代码中忘记了它。

所以你应该试试这个:

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

    // HERE set your percent rate
    $percent = 1; // 1%

    // Fee calculation
    $fee = ( $cart->subtotal - $cart->get_cart_discount_total() ) * $percent / 100;

    // Add the fee if it is bigger than O
    if( $fee > 0 )
        $cart->add_fee( __('Surcharge', 'woocommerce'), $fee, true );
}

代码进入活动子主题(或主题)的 function.php 文件中。

测试并完美运行。

注意:也很长时间以来已被替换global $woocommerce;。woocommerce对象已包含自身……</p> $woocommerce->cartWC()->cartWC()global $woocommerce;


具体更新:

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

    // HERE set your percent rate and your state
    $percent = 6;
    $state = array('MI');

    $coupon_total = $cart->get_discount_total();

    // FEE calculation
    $fee = ( $cart->subtotal - $coupon_total ) * $percent / 100;

    if ( $fee > 0 && WC()->customer->get_shipping_state() == $state )
        $cart->add_fee( __('Tax', 'woocommerce'), $fee, false);
}

代码进入活动子主题(或主题)的 function.php 文件中。

测试和工作。

于 2018-02-27T16:27:48.463 回答
1

我用来创建优惠券的插件连接到 after_calculate_totals 并在之后调整金额。在插件之前触发的任何东西都不计入调整后的总数。我能够使用插件中的变量调用特定金额来创建我需要的费用金额

对于其他感兴趣的人:我正在使用 ignitewoo 礼券 pro 插件,并希望根据优惠券后的余额收取费用。这是 Loic 的代码,经过一些修改:

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

    $state      = array('MI');

    // HERE set your percent rate
    $percent = 6;
    $coupTotal = 0;
    foreach ( $woocommerce->cart->applied_coupons as $cc ) {
    $coupon = new WC_Coupon( $cc );
    $amount = ign_get_coupon_amount( $coupon );
    $coupTotal += $amount;
    }


    // Fee calculation
    $fee = ($cart->subtotal - $coupTotal) * $percent/100;
if (( $fee > 0 ) AND  (in_array( WC()->customer->shipping_state, $state ) ))
        $cart->add_fee( __('Tax', 'woocommerce'), $fee, false);
}
于 2018-03-01T14:34:01.847 回答