使用此处显示的代码时,我希望仅创建一个名为“ Late Fee”的新订单商品。但是,当我运行代码2时,新的相同订单项记录被添加到订单中。我不知道为什么会这样,而且还无法弄清原因。你能帮忙吗?
我在代码的末尾添加了回显,以在运行代码时显示order_item_id。由于创建了2条记录,我希望回显会产生2行输出,并显示每个新的记录ID。但是,在运行代码时,仅回显了一行,并且显示了第二条记录的ID。没有回显第一个记录ID。
// 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
以下是显示2条记录的“ wp_woocommerce_order_items”表查询结果。我的“ echo”命令的输出仅显示“ 568”。所以我不知道如何或为什么创建2条记录。
order_item_id order_item_name order_item_type order_id
568滞纳金line_item 1550 567滞纳金line_item 1550
答案 0 :(得分:1)
您的代码看起来不错,但是不确定您在哪里运行了代码(它在哪钩?),还请尝试按照woocommerce的最新(从2.2版开始)api函数将产品设置为最小的方式现有订单,这是下面的代码
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;
}
我已经测试了上面的代码,看来工作正常,没有任何问题。希望对您有帮助!