add_fee()在结账总额上加两次费用

时间:2017-03-30 16:05:02

标签: php wordpress woocommerce checkout cart

我正在尝试根据用户选择的字段在结帐页面上添加费用。

当我使用WC_cart add_fee() 方法时,它会在总数上加两次费用,而在结帐时只显示一次。因此,结帐总计算错误。

以下是我正在尝试的代码:

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

    $eu_array = array('BE','BG','CZ','DK','DE','EE','IE','GR','ES','FR','HR','CY','LV','LT','LU','HU','MT','NL','AT','PT','RO','SI','SK','FI','GB');

    if(preg_match("#customer_type=company#", $_POST['post_data']) ){

        if(in_array($_POST['s_country'], $eu_array)){
            $woocommerce->cart->add_discount(sanitize_text_field( 'cart_company_dis' ));
            $ship = $cart->shipping_total;
            $shipp = $ship - ($ship*100/122);
            wc()->cart->add_fee('Exclude shipping VAT', -$shipp);
        }
    }elseif(preg_match("#customer_type=customer#", $_POST['post_data']) ){
        $woocommerce->cart->remove_coupon(sanitize_text_field( 'cart_company_dis' ));

    }
}

该代码在结帐页面上应用折扣,并根据客户类型和国家/地区增加费用。

折扣正确减少但费用增加了两倍。

如何避免此问题?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用WC_Cart方法get_fees()来检查购物车中是否已经应用了特定费用,避免了重复的费用问题。

所以你的代码会有所改变:

// NOTE: 
// No need of "global woocommerce" and "woocommerce->cart" (old syntax) replaced by "WC()->cart"
// Here "$cart_obj" replace "WC()->cart" everywhere, as it included as argument in the function…

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge',50 );
function woocommerce_custom_surcharge( $cart_obj ) {

    $eu_array = array('BE','BG','CZ','DK','DE','EE','IE','GR','ES','FR','HR',
        'CY','LV','LT','LU','HU','MT','NL','AT','PT','RO','SI','SK','FI','GB');

    if(preg_match("#customer_type=company#", $_POST['post_data']) ){

        if(in_array($_POST['s_country'], $eu_array)){
            $cart_obj->add_discount(sanitize_text_field( 'cart_company_dis' ));

            $ship = $cart_obj->shipping_total;
            $shipp = $ship - ($ship * 100 / 122);

            // Getting the cart fees
            $cart_fees = $cart_obj->get_fees();
            $has_the_fee = true;

            // Iterating through each cart fees
            foreach($cart_fees as $fee_obj)
                if( 'exclude-shipping-vat' != $fee_obj->id ){}
                    $has_the_fee = false; // Has not 'Exclude shipping VAT' fee

            // Add the fee if it doesn't exist yet (avoiding duplicate fee)
            if( empty($cart_fees) || $has_the_fee )
                $cart_obj->add_fee( __( 'Exclude shipping VAT', 'woocommerce' ), -$shipp );
        }
    } elseif( preg_match( "#customer_type=customer#", $_POST['post_data'] ) ){
        $cart_obj->remove_coupon( sanitize_text_field( 'cart_company_dis' ) );

    }
}

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

此代码经过测试并有效。