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

2023-12-27

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

有人可以告诉我如何做到这一点吗?


你需要使用新的CRUD 设置器方法 https://github.com/woocommerce/woocommerce/wiki/CRUD-Objects-in-3.0Woocommerce 3 中引入:

  • 对于订单对象,您将使用WC_Order methods https://docs.woocommerce.com/wc-apidocs/class-WC_Order.html,
  • 对于订单“订单项”,您将使用WC_Order_Item_Product methods https://docs.woocommerce.com/wc-apidocs/class-WC_Order_Item_Product.html,
  • 对于他们两个,你也可以使用一些WC_Data methods https://docs.woocommerce.com/wc-apidocs/class-WC_Data.html like save()

以下是一个具有静态价格和静态订单 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();

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改 Woocommerce 3 中的订单商品价格 的相关文章

随机推荐