Some Useful Codes on Programmatically Creating New Order in Woocommerce

Today i’m sharing with you some useful codes for creating WooCommerce orders at backend side, via your own code.

Let’s get started:

Create new order + add new product(s) to newly created order

$order = wc_create_order();
$product_ids=array(123,143,55);
$quantities=array(1,1,2);
foreach($product_ids as $key=>$value){
 $order->add_product( get_product($value), $quantities[$key] );
}
$order->calculate_totals();

Update WooCommerce order status with simple code

$order->update_status("wc-completed", 'Created via Custom Backend Code', TRUE);
//don't forget to put "wc-" prefix to WooCommerce status parameter)

How to change WooCommerce order’s created date

$date=date('Y-m-d H:i:s');
wp_update_post(array ('ID' => $order->get_id(),
'post_date'=> $date,'post_date_gmt' => get_gmt_from_date( $date )));

Create custom taxonomy for WooCommerce Orders

function register_order_type(){
    register_taxonomy(
        'custom_order_category',
        'shop_order',
        array(
            'label' => __( 'Order Category' ),
            'public' => true,
            'hierarchical' => true,
        )
    );
  }
add_action( 'init','register_order_type',9999);

Set custom taxonomy to newly created WooCommerce Order

wp_set_post_terms($order->get_id(),array(CAT_IDS_HERE),"custom_order_category");

Set custom total for WooCommerce Order

$order->set_total(10000); // = $10K

Get more useful WP tricks and snippets by subscribing to my mailclub.

2 Replies to “Some Useful Codes on Programmatically Creating New Order in Woocommerce”

Leave a Reply

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