woocommerce recalculate price programmatically

Viewed 278

11/5/21 Update

It's really tricky that find out the wc_order couldn't access the calculate_totals and calculate_taxes.I find out the solution is put $order = wc_get_order( $order->get_id() ); before calulation. The 2 $order type is different , one is (object)WC_Order and another one is (Object)Automattic\WooCommerce\Admin\Overrides\Order. The method of second object works.

I wanna make the AJAX function to place an order programmatically. The product price is base on metadata so I have to calculate every line item. It doesn't with any issue from the client side that sends the post the request to place. The problem point, even I set the price to the line item, and use calculate_totals for the WC_Order but the price didn't correct. The only correction is the cost and subtotal. Though I hit the recalculate button the price would be right.

code

function place_an_order($data){

  $screen_prodcut = new WC_Product_Simple(6310);

  $userid = get_current_user_id();
  $order = wc_create_order(array('customer_id'=>$userid));

  $screen_quantity = 2;
  $item_id =  $order->add_product($screen_prodcut,$screen_quantity);
  wc_add_order_item_meta($item_id,'width','1201');
  wc_add_order_item_meta($item_id,'height','1201');
  wc_add_order_item_meta($item_id,'note','** this is testing**');

  $screen_price = 50;
  $new_line_screen_price = $screen_price * $screen_quantity; 
  $item = $order->get_item($item_id);
  $item->set_subtotal( $new_line_screen_price / 11 * 10 ); 
  $item->set_total( $new_line_screen_price / 11 * 10 );
  $item->save();
  // ###section 1###
  $order->calculate_taxes();
  $order->calculate_totals(); 
  // ###section 2###
}

When run in section 1, the $item subtotal and total are correct. But run in section 2 there is the failure out when printing $order and retrieve the total is wrong. In the dashboard, the price would be shown wrong but the total and subtotal are correct.

enter image description here

After clicking the recalculate, the order total is corrected.

enter image description here

I have no idea why calculate_totals and calculate_taxes don't work. woocommerce_calc_line_taxes is the AJAX action via hit the recalculate button. Usage is calculate_totals and taxes as well. Alternatively, I have to use the set_total instead of calculate_totals?

0 Answers
Related