在 WooCommerce 中,我尝试根据购物车重量添加额外的运费.
In WooCommerce, I am trying to add a an additional shipping fee based on cart weight.
1500g
的费用是 50 美元.1500g
之上,我们以 1000g 为单位在最初的 50 美元基础上加 10 美元1500g
the fee is 50$.1500g
we add 10$ to this initial $50 by steps of 1000g例如:
我被困在计算上:
function weight_add_cart_fee() {
$feeaddtocart = get_option('feeaddtocart');
$customweight = get_option('customweight');
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_weight = WC()->cart->get_cart_contents_weight();
if ($cart_weight <= 500 ) {
$get_cart_total = $woocommerce->cart->get_cart_total();
$newtotal = $get_cart_total + 50;
WC()->cart->add_fee( __('Extra charge (weight): ', 'your_theme_slug'), $newtotal, false );
}
}
我怎样才能做到这一点?任何帮助表示赞赏.
How can I achieve this? Any help is appreciated.
使用 woocommerce_cart_calculate_fees
动作钩子中挂钩的自定义函数可以非常轻松地完成...
It can be done very easily with a custom function hooked in woocommerce_cart_calculate_fees
action hook…
更新:
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Convert cart weight in grams
$cart_weight = $cart->get_cart_contents_weight() * 1000;
$fee = 50; // Starting Fee below 500g
// Above 500g we add $10 to the initial fee by steps of 1000g
if( $cart_weight > 1500 ){
for( $i = 1500; $i < $cart_weight; $i += 1000 ){
$fee += 10;
}
}
// Setting the calculated fee based on weight
$cart->add_fee( __( 'Weight shipping fee' ), $fee, false );
}
代码位于活动子主题(或活动主题)的 function.php 文件中.
经过测试并有效.
这篇关于根据 Woocommerce 中的总重量添加自定义费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!