1

I'm trying to programmatically change the shipping price for an order. I've tried code similar to the following in my woocommerce_order_status_processing action hook function. I got the shipping total to update, but not the actual line item for FedEx. I'm using pluginhive's FedEx shipping plugin. Is there a way to update the FedEx value as well as the total?

$shipping = $order->get_shipping_total();
$new_shipping = 1.00;
$order->set_shipping_total($new_shipping);
$order->save();


$order->calculate_shipping();
$order->calculate_totals();
aynber
  • 22,380
  • 8
  • 50
  • 63
Jordan Carter
  • 1,276
  • 3
  • 19
  • 43
  • 2
    You need to overwrite the related **order "shipping" item** instead (by cloning it and changing amounts on cloned item, removing original and saved cloned one)… then you will be able to use `calculate_shipping()` and `calculate_totals()` methods. – LoicTheAztec Feb 26 '21 at 11:10
  • 1
    Thank you @LoicTheAztec. I posted my answer using $order->get_items( 'shipping' ). I was able to make it work without cloning (I'm not sure what you meant by that). The $qty part is probably not needed. That code was being used for order items and they are both sharing a function since some of the code is repetitive. – Jordan Carter Feb 26 '21 at 16:55
  • Yes that is the right way, see: [Add update or remove WooCommerce shipping order items](https://stackoverflow.com/questions/56038530/add-update-or-remove-woocommerce-shipping-order-items/56041391#56041391) – LoicTheAztec Feb 26 '21 at 17:04

1 Answers1

1

I ended up using something like (thanks to @LoicTheAztec for the assistance):

foreach( $order->get_items( 'shipping' ) as $item_id => $item ) {
    $item_price = $item->get_total();
    $qty = (int) $item->get_quantity();
    $item_price = ($item_price / $exchange_rate) * $qty;

    $item->set_total( $item_price );
    $item->calculate_taxes();
    $item->save();
}

$order->calculate_shipping();
$order->calculate_totals();

The quantity part may not be needed.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Jordan Carter
  • 1,276
  • 3
  • 19
  • 43