How to programatically create a new order in WooCommerce

Ever needed to make a WooCommerce order without using the online store? It’s actually quite simple to create a WooCommerce order programatically using code on the backend, and in this snippet, we’ll share with you the code needed to get it working.

Starting off, we need to hook in to an action and execute the code to create the order. There are a number of actions in WordPress and WooCommerce that we could hook in to, however, we need to make sure that we don’t hook too early, otherwise product data will not be available to us yet.

So a good action to hook in to would be the init action.

Create a WooCommerce Order programatically

Here is the snippet that you should use. You can add it to your functions.php. You most likely would want to add some logic around when to create the order. That can all be done inside the function below.

<?php
function thenga_create_new_order() {
   // Define the customer details.
   $address = array(
      'first_name' => 'John',
      'last_name'  => 'Doe',
      'company'    => 'Delicious Cupcakes',
      'email'      => 'john.doe@test.com',
      'phone'      => '530-123-1234',
      'address_1'  => '10 Church Street',
      'address_2'  => '',
      'city'       => 'New York',
      'state'      => 'NY',
      'postcode'   => '10001',
      'country'    => 'US'
   );

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

   // Add a product, make sure that this product exists!
   $order->add_product( get_product( '1' ), 1 );
   $order->set_address( $address, 'billing' );
   $order->calculate_totals();
   $order->update_status( 'Completed', 'Order note', TRUE );
}

add_action( 'init', 'thenga_create_new_order' );

Breaking it down, we simply set custom data in to an array. Then create an order object. We lastly use the order object to set details about the order like the product we’re ordering and the customer details that we defined and then we complete the order.

That’s all there is to it. If you get stuck anywhere, let us know in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.