根据 Woocommerce 中的总重量添加自定义费用

Add custom fee based on total weight in Woocommerce

在 WooCommerce 中,我试图根据购物车重量添加额外的运费。

例如:

我卡在了计算上:

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 );
    }
}

我怎样才能做到这一点?感谢任何帮助。

可以很容易地通过挂钩在 woocommerce_cart_calculate_fees 动作挂钩中的自定义函数来完成...

Updated:

  • Added conversion of cart weight in grams (instead of kilos by default)
  • Now for the first 1500g the fee is 50$ (instead of 500g)
  • Now above 1500g it add by steps of 1000g.
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  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 文件。

已测试并有效。