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

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

问题描述

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

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

  • 第一个1500g费用为50美元.
  • 1500g之上,我们以1000g为步长,将这10美元添加到初始的50美元中
  • 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美元.
  • 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 $10 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 $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文件中.

经过测试,可以正常工作.

Tested and works.

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

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