根据WooCommerce折扣后的总额添加计算费用

问题描述 投票:1回答:2

我试图根据折扣后的小计向我的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值被弃用并且总是显示零,但它没有解释为什么这些数量出现在过滤器而不是动作中。

我还可以在一个动作中使用什么来获得相同的数字并增加一定的费用?

php wordpress woocommerce cart fee
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->cart已经被WC()->cart取代了很长一段时间。 WC() woocommerce对象已经包括自己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文件中。

经过测试和工作。


1
投票

我用来创建优惠券的插件挂钩到after_calculate_totals并随后调整金额。插件之前发生的任何事情都没有计入调整后的总数。我能够使用插件中的变量调用特定金额来创建我需要的费用金额

对于任何感兴趣的人:我正在使用ignitewoo礼券自制插件,并希望根据优惠券后的余额创建费用。这是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);
}
© www.soinside.com 2019 - 2024. All rights reserved.