将定制价格的产品添加到以WooCommerce

时间:2017-12-26 18:00:06

标签: php wordpress woocommerce product orders

我正在尝试添加$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.

但订单价值不会改变。还有其他方法可以实现同样的目标吗?

2 个答案:

答案 0 :(得分:2)

我发现自己陷入了同样的困境:我需要使用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();

当您在WooCommerce仪表板中查找此订单时,它将显示您的自定义价格,而不是默认产品价格。

答案 1 :(得分:1)

以下是在创建订单时为产品添加自定义价格的方法。

假设您将在新包装的订单中设置所有其他数据和项目类型(如客户地址,税项......),因为这不是问题的一部分,并且之前已在其他线程中得到解答

代码:

## -- HERE Define everything related to your product -- ##

$product_id = '41'; // a product ID or a variation ID
$new_product_price = 120; // the new product price  <==== <==== <====
$quantity = 1; // The line item quantity

## - - - - - - - - - - - - - - - - - - - - - - - - - -  ##

// Get an instance of the WC_Product object
$product = wc_get_product( $product_id );

// Change the product price
$product->set_price( $new_product_price );

## - - - - - - - - - - - - - - - - - - - - - - - - - -  ##

// Create the order
$order = wc_create_order();

// Add the product to the order
$order->add_product( $product, $quantity);

## You will need to add customer data, tax line item … ##

$order->calculate_totals(); // updating totals

$order->save(); // Save the order data

经过测试和工作