Rah*_*hul 5 php wordpress product orders woocommerce
我正在尝试添加一个$order = wc_create_order();
由用户定义的产品价格。一个特定的产品被添加到订单中,它已经有一个默认价格,需要被用户输入的值覆盖。
我尝试使用woocommerce_before_calculate_totals
函数但没有运气。我认为它不起作用,因为产品直接添加到订单中而没有添加到购物车中。
我也试过使用set_total( $value, $deprecated = '' )
,比如
$order = wc_create_order();
$order->set_total($amount); //where the $amount is my custom price.
Run Code Online (Sandbox Code Playgroud)
但订单价值不会改变。有没有其他方法可以实现相同的目标?
以下是创建订单时包含产品自定义价格的方法。
\n\n假设您将在新创建的订单中设置所有其他数据和项目类型(例如客户地址、税项\xe2\x80\xa6),因为这不是问题的一部分,并且之前已在其他线程中得到回答
\n\n代码:
\n\n## -- HERE Define everything related to your product -- ##\n\n$product_id = '41'; // a product ID or a variation ID\n$new_product_price = 120; // the new product price <==== <==== <====\n$quantity = 1; // The line item quantity\n\n## - - - - - - - - - - - - - - - - - - - - - - - - - - ##\n\n// Get an instance of the WC_Product object\n$product = wc_get_product( $product_id );\n\n// Change the product price\n$product->set_price( $new_product_price );\n\n## - - - - - - - - - - - - - - - - - - - - - - - - - - ##\n\n// Create the order\n$order = wc_create_order();\n\n// Add the product to the order\n$order->add_product( $product, $quantity);\n\n## You will need to add customer data, tax line item \xe2\x80\xa6 ##\n\n$order->calculate_totals(); // updating totals\n\n$order->save(); // Save the order data\n
Run Code Online (Sandbox Code Playgroud)\n\n经过测试并有效
\n小智 7
我发现自己陷入了同样的困境:我需要使用 WooCommerce API 来创建具有特定产品的自定义每订单价格的订单。
事实证明,WC_Order::add_product 函数接受第三个参数,该参数允许您为“小计”和“总计”设置自定义值:
https://docs.woocommerce.com/wc-apidocs/source-class-WC_Abstract_Order.html#1109-1160
$order = wc_create_order();
$order->add_product( $product, $quantity, [
'subtotal' => $custom_price_for_this_order, // e.g. 32.95
'total' => $custom_price_for_this_order, // e.g. 32.95
] );
$order->save();
Run Code Online (Sandbox Code Playgroud)
当您在 WooCommerce 仪表板中查找此订单时,它将显示您的自定义价格而不是默认产品价格。
归档时间: |
|
查看次数: |
7386 次 |
最近记录: |