Php 从现有订单以编程方式更改发货方式
我的客户通过我的woocommerce网站购买订阅。他们每个月都会收到产品,但有时他们想改变运输方式。 我找不到通过php实现的文档Php 从现有订单以编程方式更改发货方式,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我的客户通过我的woocommerce网站购买订阅。他们每个月都会收到产品,但有时他们想改变运输方式。 我找不到通过php实现的文档 我可以更改post\u-meta、woocommerce\u-order\u-items和woocommerce\u-order\u-itemmeta中的值,但这不是一个持久的解决方案。以下是以编程方式更改订单“发货”项以定义新的发货方法id(slug): // Here set your shipping method ID replacement $new_m
我可以更改
post\u-meta
、woocommerce\u-order\u-items
和woocommerce\u-order\u-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
}
测试和工作
相关线程: