在 WooCommerce 管理端,在订单页面上,我想在付款状态更改时修改运输元数据

问题描述 投票:0回答:1

我有这个代码,我正在 WooCommerce 中尝试使用此代码,付款状态已准备好在订单页面上购物,其中显示运输的运输我想将其运输更改为 LCS Express,并且还想更新其中的运输多个选择选项,所以我想更新其他这里是我的代码,它在第二次订单更新时唯一更新 LCS Express:

function customize_order_item_display($product, $item, $item_id) {
    // Get the order ID
    $order_id = $item->get_order_id();

    // Get the order object
    $order = wc_get_order($order_id);

    // Check if the payment status is "ready-to-ship"
    if ($order->get_status() === 'ready-to-ship') {
        // Modify the shipping method
        $new_shipping_method = 'LCS Express'; // Replace with your desired shipping method

        // Get the shipping method data
        $shipping_method_data = $item->get_data()['shipping'];

        // Set the new shipping method name
        $shipping_method_data['name'] = $new_shipping_method;

        // Set the new shipping method ID
        $shipping_method_data['method_id'] = sanitize_title($new_shipping_method);

        // Update the item with the modified shipping method data
        $item->set_props(array('shipping' => $shipping_method_data));
        $item->save();

        // Modify the shipping input fields using JavaScript
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($){
                // Set the shipping method name in the input field
                $('input.shipping_method_name').val('<?php echo esc_js($new_shipping_method); ?>');
                
                // Set the shipping method ID in the select field
                $('select.shipping_method').val('<?php echo esc_js($shipping_method_data['method_id']); ?>');
            });
        </script>
        <?php
    }
}
add_action('woocommerce_admin_order_item_values', 'customize_order_item_display', 10, 3);
wordpress woocommerce hook-woocommerce
1个回答
0
投票

您没有使用正确的钩子和正确的方法(例如,方法 set_props() 不能在自定义函数中使用)。

要更改订单“运输”商品,请使用

WC_Order_Item
WC_Order_Item_Shipping
可用的 setter 方法。

当订单状态更改为“准备发货”时,最好使用专用的转换订单状态挂钩之一来更改订单。

尝试以下操作:

add_action( 'woocommerce_order_status_ready-to-ship', 'customize_order_shipping_item_on_ready_to_ship', 10, 2 );
function customize_order_shipping_item_on_ready_to_ship( $order_id, $order ) {
    // Iterating through order shipping items
    foreach( $order->get_items( 'shipping' ) as $item_id => $item ) {
        $method_name = __('LCS Express'); // New shipping method name 

        $item->set_name($method_name);
        $item->set_method_title($method_name);
        $item->set_method_id( sanitize_title($method_name) );
        $item->save();
    }
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并工作。

相关:

© www.soinside.com 2019 - 2024. All rights reserved.