在 Woocommerce 3 中以编程方式向订单添加运费 [英] Add a shipping to an order programmatically in Woocommerce 3

查看:23
本文介绍了在 Woocommerce 3 中以编程方式向订单添加运费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试多种解决方案,通过 Woocommerce 以编程方式设置运输价格(每个订单).我运气不好

I've been trying numerous solutions to programmatically set the price of shipping (per order) via Woocommerce. I'm having no luck

我尝试覆盖项目的元值:

I have tried overwriting the meta value for the item:

            update_post_meta( $woo_order_id, '_order_shipping', $new_ship_price );

也尝试过类似 [问题/答案][1]

Also tried something along the lines of this [Question/Answer][1]

                    $item_ship = new WC_Order_Item_Shipping();

                    $item_ship->set_name( "flat_rate" );
                    $item_ship->set_amount( $new_ship_price );
                    $item_ship->set_tax_class( '' );
                    $item_ship->set_tax_status( 'none' );


                    // Add Shipping item to the order
                    $order->add_item( $item_ship );

但两者似乎都不起作用.任何指针最欢迎.

But neither seem to work. Any pointers most welcome.

类似话题:在 Woocommerce 3 中以编程方式向订单添加费用

推荐答案

要在 Woocommerce 3+ 中处理此问题,请使用以下内容(来自 WC_Order 订单对象 $order):

To handle this in Woocommerce 3+ use the following (from a WC_Order Order object $order):

## ------------- ADD SHIPPING PROCESS ---------------- ##

// Get the customer country code
$country_code = $order->get_shipping_country();

// Set the array for tax calculations
$calculate_tax_for = array(
    'country' => $country_code,
    'state' => '', // Can be set (optional)
    'postcode' => '', // Can be set (optional)
    'city' => '', // Can be set (optional)
);

// Optionally, set a total shipping amount
$new_ship_price = 5.10;

// Get a new instance of the WC_Order_Item_Shipping Object
$item = new WC_Order_Item_Shipping();

$item->set_method_title( "Flat rate" );
$item->set_method_id( "flat_rate:14" ); // set an existing Shipping method rate ID
$item->set_total( $new_ship_price ); // (optional)
$item->calculate_taxes($calculate_tax_for);

$order->add_item( $item );

$order->calculate_totals();

$order->update_status('on-hold');

// $order->save(); // If you don't update the order status

测试了一个作品.

这篇关于在 Woocommerce 3 中以编程方式向订单添加运费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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