我的客户通过我的woocommerce网站购买订阅。他们每个月都会收到产品,但是他们想更改运输方式。 我找不到通过php进行操作的文档。
我可以更改post_meta
,woocommerce_order_items
和woocommerce_order_itemmeta
中的值,但这不是一个持久的解决方案。
答案 0 :(得分:1)
以下是通过编程方式更改要定义新运输方式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
}
经测试可正常工作
相关线程: