How to Create Orders Programmatically in WooCommerce: A Step-by-Step Guide

Welcome to this tutorial, where I will guide you step by step through the process of programmatically creating WooCommerce orders. This can be useful when you need to integrate WooCommerce with external systems or when you want to automate certain internal processes.

1. Preparation

Before you begin, ensure you have access to the file functions.php of your theme or, better yet, a custom plugin. This is where we will place our code.

2. Creating a Basic Order

To create an order, we need to instantiate an object of the class WC_Order. Here is a basic example:

$order = wc_create_order();

However, this order is very basic. Let's see how to add details to this order.

3. Adding Products to the Order

To add products, we use the method add_product(). Here is an example of how to add a product to our order:

$product = wc_get_product(123); // Where 123 is the product ID;

4. Setting Addresses

To set the shipping and billing addresses, we use the methods set_billing_address() y set_shipping_address():

$address = array(;

5. Adding Notes to the Order

Order notes are useful for storing additional information. Here is how to add one:

$note = "This is an example note for the order.";

6. Setting Shipping Methods

If you want to specify a shipping method, you can do so as follows:

$shipping_method = new WC_Shipping_Rate('id', 'Envío Estándar', 5.00, array(), 'flat_rate');
$order->add_shipping($shipping_method);

Make sure to adjust the values according to your configuration and needs.

7. Adding Coupons

If the customer has used a coupon, we can add it to our order programmatically:

$coupon_code = 'MY_COUPON';

8. Setting Payment Methods and Paying the Order

First, let's set the payment method:

$order->set_payment_method('bacs'); // 'bacs' is for bank transfer. Adjust according to your payment methods.

If you want to mark the order as paid:

$order->payment_complete();

9. Saving and Finalizing

It is crucial to remember to save the order after making all modifications:

$order->save();

Complete Example

Here is a complete example of how to programmatically create an order in WooCommerce, with proper checks and comments to ensure everything works correctly:

<?php
// Verificamos si WooCommerce está activo
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {

    // Creamos una nueva orden
    $order = wc_create_order();

    // Añadimos un producto a la orden (por ejemplo, el producto con ID 123)
    $product = wc_get_product(123);
    $quantity = 1;
    $order->add_product($product, $quantity);

    // Definimos una dirección para facturación y envío
    $address = array(
        'first_name' => 'Juan',
        'last_name'  => 'Pérez',
        'company'    => 'Mi Empresa',
        'email'      => 'juan@example.com',
        'phone'      => '123-456-7890',
        'address_1'  => 'Calle 123',
        'address_2'  => '', 
        'city'       => 'Madrid',
        'state'      => 'M',
        'postcode'   => '28001',
        'country'    => 'ES'
    );
    $order->set_billing_address($address);
    $order->set_shipping_address($address);

    // Añadimos una nota a la orden
    $note = "Esta es una nota de ejemplo para la orden.";
    $order->add_order_note($note);

    // Establecemos un método de envío (por ejemplo, envío estándar por 5.00)
    $shipping_method = new WC_Shipping_Rate('id', 'Envío Estándar', 5.00, array(), 'flat_rate');
    $order->add_shipping($shipping_method);

    // Aplicamos un cupón si es necesario
    $coupon_code = 'MI_CUPON';
    $order->apply_coupon($coupon_code);

    // Establecemos el método de pago y marcamos la orden como pagada
    $order->set_payment_method('bacs'); // 'bacs' es para transferencia bancaria. Ajusta según tus métodos de pago.
    $order->payment_complete();

    // Guardamos todos los cambios hechos en la orden
    $order->save();

    // Imprimimos el ID de la orden para referencia
    echo 'Se ha creado la orden con el ID: ' . $order->get_id();

} else {
    echo 'WooCommerce no está activo. Asegúrate de activarlo para proceder.';
}
?>

This code first checks if WooCommerce is active. If it is, it creates an order, adds a product, sets the addresses, adds a note, sets the shipping method, applies a coupon, sets the payment method, and finally saves the order. If WooCommerce is not active, it displays an error message.

I hope this example is useful to you and helps you in your development with WooCommerce. Let me know if there is anything else I can help you with!

Do you need help with a web project?

Do you need help with a web project? Don't hesitate to contact me. I develop complete and customized solutions with WordPress and PHP, using modern tools and processes, HTML, CSS, SCSS, PHP, JavaScript, Bootstrap, and more. Ready? Send me a message and let's talk about your web project!