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

Add custom fee based on total weight in Woocommerce(根据 Woocommerce 中的总重量添加自定义费用)
本文介绍了根据 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 中的总重量添加自定义费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)