Add update or remove WooCommerce shipping order items

雨燕双飞 提交于 2020-07-14 09:17:57

问题


I have added shipping cost for the orders that are synced from amazon. For some reason I had to set custom shipping flat price in woo-orders created for amazon-order. It is done as follow:

    $OrderOBJ = wc_get_order(2343);
    $item = new WC_Order_Item_Shipping();

    $new_ship_price = 10;

    $shippingItem = $OrderOBJ->get_items('shipping');

    $item->set_method_title( "Amazon shipping rate" );
    $item->set_method_id( "amazon_flat_rate:17" );
    $item->set_total( $new_ship_price );
    $OrderOBJ->update_item( $item );

    $OrderOBJ->calculate_totals();
    $OrderOBJ->save()

The problem is, I have to update orders in each time the status is changed in amazon, there is no problem doing that, problem is I have to update the shipping cost also if it is updated. But I have not found anyway to do so. Can anyone tell me how to update the shipping items of orders set in this way ? Or is it the fact that, once shipping item is set then we cannot update or delete it ? Any kinds of suggestion are highly appreciated. Thanks.


回答1:


To add or update shipping items use the following:

$order_id = 2343;
$order    = wc_get_order($order_id);
$cost     = 10;
$items    = (array) $order->get_items('shipping');
$country  = $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)
);

if ( sizeof( $items ) == 0 ) {
    $item  = new WC_Order_Item_Shipping();
    $items = array($item);
    $new_item = true;
}

// Loop through shipping items
foreach ( $items as $item ) {
    $item->set_method_title( __("Amazon shipping rate") );
    $item->set_method_id( "amazon_flat_rate:17" ); // set an existing Shipping method rate ID
    $item->set_total( $cost ); // (optional)

    $item->calculate_taxes( $calculate_tax_for ); // Calculate taxes

    if( isset($new_item) && $new_item ) {
        $order->add_item( $item );
    } else {
        $item->save()
    }
}
$order->calculate_totals();

It should better work…


To remove shipping items use te following:

$order_id = 2343;
$order    = wc_get_order($order_id);
$items    = (array) $order->get_items('shipping');

if ( sizeof( $items ) > 0 ) {
    // Loop through shipping items
    foreach ( $items as $item_id => $item ) {
        $order->remove_item( $item_id );
    }
    $order->calculate_totals();
}

Related: Add a shipping to an order programmatically in Woocommerce 3



来源:https://stackoverflow.com/questions/56038530/add-update-or-remove-woocommerce-shipping-order-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!