I am trying to add a$order = wc_create_order();
where the price of the product is defined by the user. A particular product is added to the order which already has a default price which needs to be overridden by the value that user has entered.
I tried using woocommerce_before_calculate_totals
function but with no luck. I assume it does not work as the product is directly added to the order witout being added to the cart.
I have also tried using the set_total( $value, $deprecated = '' )
, like
$order = wc_create_order();
$order->set_total($amount); //where the $amount is my custom price.
but the order value doesn't change. is there any other way to achieve the same?
function create_vip_order() { global $woocommerce; $address = array( 'first_name' => '111Joe', 'last_name' => 'Conlin', 'company' => 'Speed Society', 'email' => '[email protected]', 'phone' => '760-555-1212', 'address_1' => '123 Main st.
I found myself in the same predicament: I needed to use the WooCommerce API to create orders with custom, per-order prices on specific products.
It turns out that the WC_Order::add_product function accepts a third parameter that allows you to set a custom value for 'subtotal' and 'total':
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();
When you look up this order in the WooCommerce dashboard, it will show your custom price instead of the default product price.
Here is the way to include a custom price for a product when creating an Order.
Assuming that you will set in the newly crated order all other data and items types (like customer address, taxes item…) as this is not part of the question and has already been answered before in other threads
The code:
## -- 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
Tested and works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With