Reputation: 6108
I'd like to create an order programmatically (for an API) and also set shipping method.
I have tried with this code:
$item = new WC_Order_Item_Shipping();
$item->set_method_title( "Flat rate" );
$item->set_method_id( "12" ); // set an existing Shipping method rate ID // was flat_rate:12
$item->set_instance_id( "12" ); // set an existing Shipping method rate ID // was flat_rate:12
//$item->set_total( $new_ship_price ); // (optional)
$order->add_item( $item );
But it has several caveats, for instance; I have to type the method title. I'd like it to just fetch from the shipping methods data already entered in WordPress (e.g. Local Pickup, GLS, etc)
Upvotes: 3
Views: 1268
Reputation: 91
function mwb_create_custom_order() {
global $woocommerce;
$address = array(
'first_name' => 'mwbtest',
'last_name' => 'mwb',
'company' => 'makewebbetter',
'email' => '[email protected]',
'phone' => '760-555-1212',
'address_1' => 'mwb',
'address_2' => '104',
'city' => 'San Diego',
'state' => 'Ca',
'postcode' => '92121',
'country' => 'US'
);
// Now we create the order
$order = wc_create_order();
$item = new WC_Order_Item_Shipping();
$item->set_method_id( 15 );
$item->set_method_title( 'Flate rate' );
$item->set_total(20);
$shipping_id = $item->save();
$order->add_item( $item );
$order->add_product( wc_get_product( '21' ), 1 );
$order->set_address( $address, 'billing' );
$order->calculate_totals();
}
add_action( 'init', 'mwb_create_custom_order');
Upvotes: 4