How to Use WooCommerce Save Order Hook

How to Use WooCommerce Save Order HookAs a WooCommerce developer, one of the most common customization you will work on from time to time is the order. There are several custom options you can implement when dealing with WooCommerce order management.

In my previous tutorials I have shared several tips on how to change the WooCommerce order status, how to customize the order emails, and ultimately how to change the default WooCommerce redirect after checkout.

To get the best from the order placing process in WooCommerce for purposes of customization of the default process of order events in WooCommerce you need to understand the WooCommerce save order hook.

This is an important point that you will use to add customization options that you can run as the order is saved in the WordPress database.

WordPress database is an important topic that all WooCommerce and WordPress developers need to understand, I shared an in-depth article on everything you need to know about WordPress database. It can be a great place to start if you are a complete beginner in WooCommerce development.

It is also important that from the development perspective you understand WooCommerce orders work like WordPress custom post types and the saving process occurs in a similar manner to the saving process of the custom post types.

WooCommerce Save Order Hook

To get the moment the order is saved the best approach is to use the wp_insert_post() or the wc_create_order() function this can be an ideal solution when you are creating the custom order programmatically.

To create WooCommerce order programmatically  you can use the code below :

[php] add_action(‘woocommerce_checkout_process’, ‘create_custom_order_programmatically’);

function create_custom_order_programmatically() {

global $woocommerce;

$address = array(
‘first_name’ => ‘Joe’,
‘last_name’ => ‘Njenga’,
‘company’ => ‘njengah’,
’email’ => ‘joe@testing.com’,
‘phone’ => ‘123-456’,
‘address_1’ => ‘123 Main st.’,
‘address_2’ => ‘104’,
‘city’ => ‘Nairobi’,
‘state’ => ‘NB’,
‘postcode’ => ‘92121’,
‘country’ => ‘KE’
);

// Now we create the order
$order = wc_create_order();

$order->add_product( get_product(‘XXXX’), 1); // This is an existing SIMPLE product
$order->set_address( $address, ‘billing’ );
//
$order->calculate_totals();
$order->update_status("Completed", ‘Imported order’, TRUE);
}
[/php]

You can alter this code to capture an external event that you want to add to your process of saving the order.  Alternatively, you can use the woocommerce_new_order hook that works from the frontend but may now work when you are creating the order from the dashboard.

Conclusion

In this post, we have outlined the various approaches you can use to get the order during the saving process and alter it to suit your custom needs.

Similar Articles

  1. How to Change Database Password In WordPress