php - 从现有的 WooCommerce 订单以编程方式更改运输方式
问题描述
我的客户通过我的 woocommerce 网站购买订阅。他们每个月都会收到产品,但有时他们想更改运输方式。我找不到通过 php 执行此操作的文档。
我可以更改 中的值,post_meta
但这不是一个持久的解决方案。woocommerce_order_items
woocommerce_order_itemmeta
解决方案
这是以编程方式更改订单“运输”项目以定义新运输方式 ID (slug ) 的方法:
// Here set your shipping method ID replacement
$new_method_id ='flat_rate';
// Get the the WC_Order Object from an order ID (optional)
$order = wc_get_order( $order_id );
// Array for tax calculations
$calculate_tax_for = array(
'country' => $order->get_shipping_country(),
'state' => $order->get_shipping_state(), // (optional value)
'postcode' => $order->get_shipping_postcode(), // (optional value)
'city' => $order->get_shipping_city(), // (optional value)
);
$changed = false; // Initializing
// Loop through order shipping items
foreach( $order->get_items( 'shipping' ) as $item_id => $item ){
// Retrieve the customer shipping zone
$shipping_zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $item->get_instance_id() );
// Get an array of available shipping methods for the current shipping zone
$shipping_methods = $shipping_zone->get_shipping_methods();
// Loop through available shipping methods
foreach ( $shipping_methods as $instance_id => $shipping_method ) {
// Targeting specific shipping method
if( $shipping_method->is_enabled() && $shipping_method->id === $new_method_id ) {
// Set an existing shipping method for customer zone
$item->set_method_title( $shipping_method->get_title() );
$item->set_method_id( $shipping_method->get_rate_id() ); // set an existing Shipping method rate ID
$item->set_total( $shipping_method->cost );
$item->calculate_taxes( $calculate_tax_for );
$item->save();
$changed = true;
break; // stop the loop
}
}
}
if ( $changed ) {
// Calculate totals and save
$order->calculate_totals(); // the save() method is included
}
测试和工作
相关话题:
推荐阅读
- arrays - Angular 8:检查数组包含组件视图中的字符串值在 IE 中不起作用
- eclipse - Eclipse GIT 对单个文件的拉取和推送操作
- rest - 如何从气流休息 api 获取失败状态 dag 的气流 dag 错误信息?
- node.js - Nodejs 在 haproxy 后面表达 web 后端
- c++ - 使用 std::accumulate 查找数组的总和
- node.js - 使用 node.js 读取 csv 文件
- node.js - Sequelize.js - bulkCreate 退货单
- ruby - 如何测试 ruby 的初始化方法,该方法又调用私有方法
- r - left_join 列表中跨多个数据帧的数据帧
- elasticsearch - 未能在索引中匹配/搜索