【问题标题】:Add custom fee based on total weight in Woocommerce根据 Woocommerce 中的总重量添加自定义费用
【发布时间】:2022-01-26 21:08:54
【问题描述】:

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

  • 第一个1500g 的费用为 50 美元。
  • 1500g 之上,我们以 1000g 为增量在最初的 50 美元基础上加 10 美元

例如:

  • 如果购物车重量为 700 克,我们将加收 50 美元的费用,
  • 如果购物车重量为 2600 克,我们将加收 70 美元(50 美元 + 10 美元 +10 美元)的费用……

我卡在计算上:

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

我怎样才能做到这一点?任何帮助表示赞赏。

【问题讨论】:

    标签: php wordpress woocommerce cart fee


    【解决方案1】:

    使用 woocommerce_cart_calculate_fees 动作钩子挂钩的自定义函数可以非常轻松地完成...

    更新:

    • 添加了以克为单位的购物车重量转换(默认情况下不是公斤)
    • 现在前 1500 克的费用是 50 美元(而不是 500 克)
    • 现在超过 1500 克,按 1000 克递增 10 美元。
    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 文件中。

    经过测试并且有效。

    【讨论】:

    • 不工作 ,,, 它告诉我 500 内部服务器错误!!更改国家后,,, 如果购物车总重量 60 克,, 则加 10 美元但不是真的,,, 必须在 1500 克后加
    猜你喜欢
    • 2015-06-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    相关资源
    最近更新 更多