通过 WooCommerce 中的管理员编辑订单自动添加或更新自定义费用

2024-05-07

我们有一个特殊情况,我们会在收到订单后向客户开具付款发票,而不是让他们在结账时付款。运费是手动计算的并添加到订单中,然后我们在总额中添加 3% 的信用卡费用。

为了自动化此过程,我创建了一个脚本,一旦通过后端设置了运费,该脚本就会计算 3% 的费用,并自动将此费用项添加到订单中。当我们添加运费并单击“保存/重新计算”时,此操作有效first time.

add_action( 'woocommerce_order_after_calculate_totals', "custom_order_after_calculate_totals", 10, 2);
function custom_order_after_calculate_totals($and_taxes, $order) {

    if ( did_action( 'woocommerce_order_after_calculate_totals' ) >= 2 )
    return;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 0.03;
    $total = $order->get_total();
    $surcharge = $total * $percentage;
    $feeArray = array(
        'name' => '3% CC Fee',
        'amount' =>  wc_format_decimal($surcharge),
        'taxable' => false,
        'tax_class' => ''
    );

    //Get fees
    $fees = $order->get_fees();
    if(empty($fees)){
        //Add fee
        $fee_object = (object) wp_parse_args( $feeArray );
        $order->add_fee($fee_object);
    } else {
        //Update fee
        foreach($fees as $item_id => $item_fee){
            if($item_fee->get_name() == "3% CC Fee"){
                $order->update_fee($item_id,$feeArray);
            }
        }
    }
}

如果我们不小心添加了错误的运费并尝试更新它,上面的代码确实会再次触发并更新费用$total不会从更新的运费中获得新的订单总额,因此费用不会改变。奇怪的是,如果我尝试删除费用项目,则会计算新的费用并用正确的费用金额加回。

有人知道我该如何解决这个问题吗?


由于您使用订单总计来计算您的费用,并且您使用的挂钩位于内部calculate_totals()方法,一旦订单更新,您始终需要按“重新计算”按钮才能获得正确的费用总额和正确的订单总金额以及正确的金额.

自 WooCommerce 3 以来,您的代码已经过时,并且有些过时,并且存在一些错误......例如add_fee() https://github.com/woocommerce/woocommerce/blob/4.8.0/includes/legacy/abstract-wc-legacy-order.php#L105-L106 and update_fee() https://github.com/woocommerce/woocommerce/blob/4.8.0/includes/legacy/abstract-wc-legacy-order.php#L261-L262方法已被弃用并被其他一些方法取代。

请改用以下内容:

add_action( 'woocommerce_order_after_calculate_totals', "custom_order_after_calculate_totals", 10, 2 );
function custom_order_after_calculate_totals( $and_taxes, $order ) {
    if ( did_action( 'woocommerce_order_after_calculate_totals' ) >= 2 )
        return;

    $percentage = 0.03; // Fee percentage

    $fee_data   = array(
        'name'       => __('3% CC Fee'),
        'amount'     => wc_format_decimal( $order->get_total() * $percentage ),
        'tax_status' => 'none',
        'tax_class'  => ''
    );

    $fee_items  = $order->get_fees(); // Get fees

    // Add fee
    if( empty($fee_items) ){
        $item = new WC_Order_Item_Fee(); // Get an empty instance object

        $item->set_name( $fee_data['name'] );
        $item->set_amount( $fee_data['amount'] );
        $item->set_tax_class($fee_data['tax_class']);
        $item->set_tax_status($fee_data['tax_status']);
        $item->set_total($fee_data['amount']);

        $order->add_item( $item );
        $item->save(); // (optional) to be sure
    }
    // Update fee
    else {
        foreach ( $fee_items as $item_id => $item ) {
            if( $item->get_name() === $fee_data['name'] ) {
                $item->set_amount($fee_data['amount']);
                $item->set_tax_class($fee_data['tax_class']);
                $item->set_tax_status($fee_data['tax_status']);
                $item->set_total($fee_data['amount']);
                $item->save();
            }
        }
    }
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。

一旦订单更新并且按重新计算按钮后 (以获得正确的订单总数)自动添加和更新的费用都会很好地工作。

有关的:在 Woocommerce 3 中以编程方式向订单添加费用 https://stackoverflow.com/questions/53603746/add-a-fee-to-an-order-programmatically-in-woocommerce-3/53604944#53604944


Update

现在,如果它因任何原因不起作用,您应该删除相关项目进行更新并添加新项目,如下所示:

add_action( 'woocommerce_order_after_calculate_totals', "custom_order_after_calculate_totals", 10, 2 );
function custom_order_after_calculate_totals( $and_taxes, $order ) {
    if ( did_action( 'woocommerce_order_after_calculate_totals' ) >= 2 )
        return;

    $percentage = 0.03; // Fee percentage

    $fee_data   = array(
        'name'       => __('3% CC Fee'),
        'amount'     => wc_format_decimal( $order->get_total() * $percentage ),
        'tax_status' => 'none',
        'tax_class'  => ''
    );

    $fee_items  = $order->get_fees(); // Get fees

    // Add fee
    if( empty($fee_items) ){
        $item = new WC_Order_Item_Fee(); // Get an empty instance object

        $item->set_name( $fee_data['name'] );
        $item->set_amount( $fee_data['amount'] );
        $item->set_tax_class($fee_data['tax_class']);
        $item->set_tax_status($fee_data['tax_status']);
        $item->set_total($fee_data['amount']);

        $order->add_item( $item );
        $item->save(); // (optional) to be sure
    }
    // Update fee
    else {
        foreach ( $fee_items as $item_id => $item ) {
            if( $item->get_name() === $fee_data['name'] ) {
                $item->remove_item( $item_id ); // Remove the item

                $item = new WC_Order_Item_Fee(); // Get an empty instance object

                $item->set_name( $fee_data['name'] );
                $item->set_amount( $fee_data['amount'] );
                $item->set_tax_class($fee_data['tax_class']);
                $item->set_tax_status($fee_data['tax_status']);
                $item->set_total($fee_data['amount']);

                $order->add_item( $item );
                $item->save(); // (optional) to be sure
            }
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 WooCommerce 中的管理员编辑订单自动添加或更新自定义费用 的相关文章

  • 如何获取与 PHP 中的日期数组相比最接近的日期

    这个帖子 https stackoverflow com questions 11012891 how to get most recent date from an array of dates几乎为我回答了这个问题 但我有一个特定的需求
  • 如何使用 facebook 用户登录我的网站?

    我想知道 facebook 如何让用户登录我们的网站 我的意思是用户需要注册到我的网站才能发表评论 我如何通过我的 php 代码检查它是否是登录用户 我听说你只能用javascript检查它是否是登录用户 感谢您的任何解释 您可以使用脸书
  • Zend 1.11 和 Doctrine 2 自动从现有数据库生成所需的一切

    我是 ORM 新手 我真的很想学习它 我按照本教程成功地使用 Zend 1 11 x 安装了 Doctrine 2 1 的所有类和配置 http www zendcasts com unit testing doctrine 2 entit
  • 将 php filter_var 与 mysql_real_escape_string 结合使用

    我想首先说 我意识到 PDO mysqli 是新标准 并且已被 SO 广泛覆盖 然而 在这种特殊情况下 我没有时间在启动客户端站点之前将所有查询转换为 PDO 以下内容已在网站上的大多数查询中使用 我可以补充一下 这不是我所使用的 user
  • 如何在xampp中启用zip.dll

    你好 我正在使用 Windows 版 xampp 我想运行 https github com johmue mysql workbench schema exporter 导出我的架构 我在 mysql 工作台中创建架构并保存它 当我运行程
  • 使用 shell_exec 将 PHP 转换为 Powershell

    如果我运行 output shell exec powershell get service dhcp 我得到了 dhcp 服务的完美输出 显示正在运行 但如果我运行 output shell exec powershell get use
  • 使用服务帐户插入 Google 日历条目

    我正在尝试使用服务帐户在 Google 日历上创建条目 我真的很接近这一点 但最后一行行不通 我得到一个500 Internal Service Error当我让它运行时 否则 程序运行时不会出错 无论其价值如何 The Calendar
  • Graph API / FQL 不返回页面的所有事件

    脸书页面 http facebook com getwellgabby events http facebook com getwellgabby events 目前有 8 个活动 我能看到他们 非管理员可以看到它们并可以加入它们 但是 当
  • 通过 PHP CURL 添加 Google 联系人

    我已经成功地通过 Zend Framework 和 PHP 将联系人添加到 google 我也希望能够通过 CURL 来做到这一点 有人有关于如何执行此操作的良好教程吗 我终于能够通过 CURL 和访问令牌来做到这一点 首先 我要说的是OA
  • 如何简单地检查服务器PHP版本是否为5或以上?

    我正在为程序创建预安装清单 该程序需要 PHP5 因此我需要检查列表脚本来检查 PHP5 的可用性 有一个函数为phpversion 将以以下格式返回5 3 6或类似的 然而 我希望清单非常简单 只是告诉你是或否 所以显示当前版本对我没有多
  • PHP session_destroy() 警告会话对象销毁失败[重复]

    这个问题在这里已经有答案了 我有这个 php 脚本 但在破坏会话时遇到问题 我收到这个警告 警告 session destroy 会话对象销毁失败 第 6 行 C xampp htdocs template nota finalizare
  • 将 Php 数组编码为 json [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我想对我的 php 数组进行编码 A
  • WooCommerce:检查商品是否已在购物车中

    我从中发现了这个很棒的片段website https joebuckle me quickie woocommerce check if item already in cart 以下是检查购物车中是否存在特定产品的函数 function
  • 找时间通过 PHP 执行 MySQL 查询

    我在互联网上看到过这个问题 here http www phpbuilder com board showthread php t 2100256 and here http answers yahoo com question index
  • PHP $_SERVER['REMOTE_HOST'] 返回 ::1 [重复]

    这个问题在这里已经有答案了 可能的重复 应该 ip SERVER REMOTE ADDR 在 mamp 本地主机上返回 1 https stackoverflow com questions 3699454 should ip server
  • 如何在索引视图中打印关联数据

    subjects this gt Subjects gt find all contain gt Users fields gt Users username Users email gt hydrate false gt toArray
  • Laravel Redis 配置

    我目前正在使用 Laravel 和 Redis 创建一个应用程序 几乎一切都工作正常 我按照文档中的说明扩展了身份验证 用户可以订阅 登录 注销 我可以创建内容 所有内容都存储在 Redis 中 但我有一个问题 我无法运行 php arti
  • 显示带有 id 的内部连接的名称[重复]

    这个问题在这里已经有答案了 我有这个查询 select from countrysegments inner join country on countrysegments country id country id inner join
  • 我可以在 php 中的 SESSION 数组上使用 array_push 吗?

    我有一个想要在多个页面上使用的数组 因此我将其设为 SESSION 数组 我想添加一系列名称 然后在另一个页面上 我希望能够使用 foreach 循环来回显该数组中的所有名称 这是会议 SESSION names 我想使用 array pu
  • 使用 .htaccess 进行 PHP 设置时出现 500 内部服务器错误

    当我使用时 htaccess对于以下 PHP 设置 我得到500 Internal Server Error访问网站时 中的代码 htaccess file php flag display errors off php flag log

随机推荐