根据 Woocommerce 中的总重量添加自定义费用 [英] Add custom fee based on total weight in Woocommerce

查看:27
本文介绍了根据 Woocommerce 中的总重量添加自定义费用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In WooCommerce, I am trying to add a an additional shipping fee based on cart weight.

  • 第一个 1500g 的费用是 50 美元.
  • 1500g 之上,我们以 1000g 为单位在最初的 50 美元基础上加 10 美元
  • For the first 1500g the fee is 50$.
  • Above 1500g we add 10$ to this initial $50 by steps of 1000g

例如:

  • 如果购物车重量为 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 );
    }
}

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

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…

更新:

  • 添加了以克为单位的购物车重量转换(而不是默认公斤)
  • 现在前 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 文件中.

经过测试并有效.

这篇关于根据 Woocommerce 中的总重量添加自定义费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆