wc_create_order

Create a new order programmatically.

Description

(WC_Order|WP_Error) wc_create_order( (array) $args = array() ); 

Returns a new order object on success which can then be used to add additional data.

Returns (WC_Order|WP_Error)

Parameters (1)

0. $args — Optional. (array) => array()
The args.

Usage

  1. if ( !function_exists( 'wc_create_order' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-core-functions.php'; 
  3.  
  4. // The args. 
  5. $args = array(); 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wc_create_order($args); 
  9.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-core-functions.php  
  1. function wc_create_order( $args = array() ) { 
  2. $default_args = array( 
  3. 'status' => null,  
  4. 'customer_id' => null,  
  5. 'customer_note' => null,  
  6. 'parent' => null,  
  7. 'created_via' => null,  
  8. 'cart_hash' => null,  
  9. 'order_id' => 0,  
  10. ); 
  11.  
  12. try { 
  13. $args = wp_parse_args( $args, $default_args ); 
  14. $order = new WC_Order( $args['order_id'] ); 
  15.  
  16. // Update props that were set (not null) 
  17. if ( ! is_null( $args['parent'] ) ) { 
  18. $order->set_parent_id( absint( $args['parent'] ) ); 
  19.  
  20. if ( ! is_null( $args['status'] ) ) { 
  21. $order->set_status( $args['status'] ); 
  22.  
  23. if ( ! is_null( $args['customer_note'] ) ) { 
  24. $order->set_customer_note( $args['customer_note'] ); 
  25.  
  26. if ( ! is_null( $args['customer_id'] ) ) { 
  27. $order->set_customer_id( is_numeric( $args['customer_id'] ) ? absint( $args['customer_id'] ) : 0 ); 
  28.  
  29. if ( ! is_null( $args['created_via'] ) ) { 
  30. $order->set_created_via( sanitize_text_field( $args['created_via'] ) ); 
  31.  
  32. if ( ! is_null( $args['cart_hash'] ) ) { 
  33. $order->set_cart_hash( sanitize_text_field( $args['cart_hash'] ) ); 
  34.  
  35. // Update other order props set automatically 
  36. $order->set_currency( get_woocommerce_currency() ); 
  37. $order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) ); 
  38. $order->set_customer_ip_address( WC_Geolocation::get_ip_address() ); 
  39. $order->set_customer_user_agent( wc_get_user_agent() ); 
  40. $order->save(); 
  41. } catch ( Exception $e ) { 
  42. return new WP_Error( error, $e->getMessage() ); 
  43.  
  44. return $order;