I want to create a new order programmatically.
Workflow is simple: After submitting simple form, user will be created and along with that, a new order.
I managed to create a new user and user_id is returned, now I need to assign a new order all in one step.
How can I accomplish this?
There's a much easier way of doing it, using
wc_create_order()
. Here's an example, which also adds shipping and product line items. It also creates a Woocommerce subscription, but you can ignore that part for a normal product, the same code will work.For creating New order, You will have to create Object of
WC_Order
, If you working outside WooCommerce or infunction.php
then, First Define Global$woocommerce
variable.So, There will be just 2 line of Code.
Hope, It will help You.
Here's how I programmatically create my orders. I largely followed WC_Checkout::create_order() from @pavel's suggestion above. This is directly from a plugin I'm writing so you'll have to adjust where the source data comes form.
Order Class
The is the interim class I use to store the orders before importing into WordPress / WooCommerce.
Add Order
The data here is imported from a PayPal CSV download of historical transactions. The $row variable represents one row in the CSV. You can adjust this to suit your needs.
in woocommerce WC_Checkout class has a "create_order" method. You can clone WC_Checkout class, give it another name, change the code of the method for your purposes and call like
in form handler
Unfortunately, I don't think there are no easy way to do this I'm afraid.
You need to add the order post using
wp_insert_post();
and then add all the meta data usingupdate_post_meta()
. You then need to add the usingwoocommerce_add_order_item()
andwoocommerce_add_order_item_meta()
. Lasty you need to set the order status usingwp_set_object_terms()
.It's quite a lot of steps and pitfalls. You need to check your database carefully and add all the data and meta data you need to process and complete the order.
have a look at my solution: creating Woocommerce order with line_item programmatically
Works like a charm and goes to the correct WC class that is used by the new REST API