Reputation: 87
When using the code shown here I am expecting only one new order item to be created called "Late Fee." However, when I run the code 2 new identical order item records are being added to the order. I don't know why this is happening and haven't been able to figure out why. Can you help?
I have added an echo at the end of the code to display the order_item_id when the code is run. Since 2 records are being created I expected the echo to produce 2 lines of output with each of the new record ids showing. However, upon running the code only one line was echoed and it showed the id of the 2nd record. The first record id was not echoed.
// set variables for code simplification
$product_id = '1579'; // late fee product
$product_name = 'Late Fee';
$price = 5;
$quantity = 1;
$total = $price * $quantity;
$order_id = '1550';
// add an order item linked to a product
$order_item_id = wc_add_order_item( $order_id, array(
'order_item_name' => $product_name,
'order_item_type' => 'line_item', // indicates product
));
wc_add_order_item_meta( $order_item_id, '_qty', $quantity, true ); // quantity
wc_add_order_item_meta( $order_item_id, '_product_id', $product_id, true ); // ID of the product
// add "_variation_id" meta
wc_add_order_item_meta( $order_item_id, '_line_subtotal', $price, true ); // price per item
wc_add_order_item_meta( $order_item_id, '_line_total', $total, true ); // total price
// recalcuate order totals
$order = new WC_Order( $order_id );
$order->calculate_totals();
echo 'Done: ' . $order_item_id . '<br>'; // echo order_item_id for debugging
Following is the "wp_woocommerce_order_items" table query results showing the 2 records. The output from my "echo" command only shows "568". So I have no clue how or why 2 records are being created.
order_item_id order_item_name order_item_type order_id
568 Late Fee line_item 1550 567 Late Fee line_item 1550
Upvotes: 0
Views: 464
Reputation: 8070
Your code looks good, but not sure where you have run the code(which hook it is?), Also try to implement the minimal way as per the latest(from version 2.2) api function of woocommerce to set the product to the existing order, here is the below code
function so_58405406_add_product_to_existing_order($order_id) {
$order = wc_get_order($order_id);
$late_fee_product_id = '1579';
$quantity = 1;
$order->add_product(get_product($late_fee_product_id), $quantity);
$order->calculate_totals();
return $order_id;
}
I have tested the above code and it seems works fine without any issue. Hope it helps!!!
Upvotes: 1