Website Building » WooCommerce » How Do I Create an Order Programmatically in WooCommerce?

How Do I Create an Order Programmatically in WooCommerce?

Last updated on January 15, 2023 @ 11:26 am

If you’re running a WooCommerce store, there may come a time when you need to programmatically create an order. For example, you may want to create an order programmatically when a customer completes a form on your site that isn’t directly connected to WooCommerce. In this article, we’ll show you how to programmatically create an order in WooCommerce.

Creating an order programmatically is fairly simple. You just need to gather the necessary data and then use the WC_Order class to create the order.

First, you need to gather the following data:

  • Customer information (name, email, etc)
  • Billing and shipping address information
  • Product information (name, SKU, price, etc)

Once you have this data, you can use the WC_Order:create() method to programmatically create an order.

Here’s a basic example of how to programmatically create an order in WooCommerce:

$billing_address = array(
'first_name' => 'John',
'last_name' => 'Doe',
'company' => 'Doe Inc.',
'email' => 'john@doe.com',
'phone' => '555-555-5555',
'address_line_1' => '', // Billing address line 1 (Street address)
'address_line_2' => '', // Billing address line 2 (Apartment, suite, unit etc.)
'city' => '', // City
'state' => '', // State or county
'postcode' => '', // Postcode or ZIP code
'country' => '' // Country
);

$shipping_address = array(
'first_name' => '',
'last_name' => '',
'company' => '',
'email' => '',
'phone' => ''
);

$products = array(
array(
'id' => '', // Product ID or SKU
),
);

try {
$order = wc_create_order();
$order->set_customer_id(get_current_user_id());
$order->set_billing_first_name($billing_address['first_name']);
$order->set_billing_last_name($billing_address['last_name']);
$order->set_billing_company($billing_address['company']);

foreach ($products as $product) {
$order->add($product);
}

if ($order->get('status') === false) {
throw new Exception('An error occurred while creating the order');
}

echo "Created order {$order->get('status')}. Thank you! ";

} catch (Exception $e) {
echo "Error creating order";
}
?>
PRO TIP: If you are not a developer, or are not comfortable working with code, do not attempt to programmatically create orders in WooCommerce. This is an advanced topic and can lead to unexpected results if not done correctly.

Creating an order programmatically is a fairly simple process. Just make sure you have all the necessary data before using the WC__Order:create() method.

Kathy McFarland

Kathy McFarland

Devops woman in trade, tech explorer and problem navigator.