在 Woocommerce 3 中更改订单商品价格

Ser*_*íos 3 php wordpress orders woocommerce price

我需要更改 woocommerce 订单中的商品价格,但我发现的所有内容都是更改购物车中的价格,但这不是我需要的,因为我需要在结帐流程后更改。

有人可以给我一个关于如何做到这一点的线索吗?

Loi*_*tec 9

您需要使用Woocommerce 3 引入的新CRUD setter 方法

这是一个带有静态价格和静态订单 ID 的工作基本示例:

$order_id = 809; // Static order Id (can be removed to get a dynamic order ID from $order_id variable)

$order = wc_get_order( $order_id ); // The WC_Order object instance

// Loop through Order items ("line_item" type)
foreach( $order->get_items() as $item_id => $item ){
    $new_product_price = 50; // A static replacement product price
    $product_quantity = (int) $item->get_quantity(); // product Quantity
    
    // The new line item price
    $new_line_item_price = $new_product_price * $product_quantity;
    
    // Set the new price
    $item->set_subtotal( $new_line_item_price ); 
    $item->set_total( $new_line_item_price );

    // Make new taxes calculations
    $item->calculate_taxes();

    $item->save(); // Save line item data
}
// Make the calculations  for the order and SAVE
$order->calculate_totals();
Run Code Online (Sandbox Code Playgroud)

然后,您必须将静态价格替换为您在自定义页面中提交的新价格,这不是那么简单,因为您需要定位正确的$item_id……