I have written the following function in a custom php function that is designed to update a recurring fee amount associated with a woo commerce subscription, where such fee amount is based on a subscription meta field which I have stored the value for in $pickup_location_fee
'''
$updated_fee = 0;
foreach ( $subscription->get_items('fee') as $item_id => $item ) {
$name = $item->get_name();
if ($name == 'Selected Location Pickup Fee') {
wc_update_order_item_meta( $item_id, "_fee_amount", $pickup_location_fee);
wc_update_order_item_meta( $item_id, "_line_total", $pickup_location_fee);
$updated_fee = 1;
}
}
// add new pickup fee if not present
if ($updated_fee == 0) {
$item_id = wc_add_order_item($subscription->get_id(), array('order_item_name' => 'Selected Location Pickup Fee', 'order_item_type' => 'fee'));
if ($item_id) {
wc_update_order_item_meta( $item_id, "_fee_amount", $pickup_location_fee);
wc_update_order_item_meta( $item_id, "_line_total", $pickup_location_fee);
}
}
// END update order item with Selected Location Pickup Fee
''' This function works as expected to change the amount of _fee_amount and _line_total fields.
My challenge is that the fee is being added, but the subscription cart total is not being updated to reflect it. When I add the following code at the bottom of the previous snippet in an attempt to recalculate the cart, not only does the cart not recalculate, but it seems to somehow inhibit the previous code from working. And the updated _fee_amount and _line_total fields set in the earlier snippet are not saved to the database.
$subscription->calculate_totals();
$subscription->save();
Is someone able to help me figure out the proper way to get the cart to recalculate after modifying these order_line_item_meta?
Thank you, Josh