Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save corsonr/d661b88408f6ea373dcee62d310de359 to your computer and use it in GitHub Desktop.
Save corsonr/d661b88408f6ea373dcee62d310de359 to your computer and use it in GitHub Desktop.
Create a WooCommerce Order Dynamically
<?php
/*
* Create order dynamically
*/
add_action( 'woocommerce_before_checkout_form', 'create_order' );
function create_order() {
global $woocommerce;
$address = array(
'first_name' => 'Remi',
'last_name' => 'Corson',
'company' => 'Automattic',
'email' => 'no@spam.com',
'phone' => '123-123-123',
'address_1' => '123 Main Woo st.',
'address_2' => '100',
'city' => 'San Francisco',
'state' => 'Ca',
'postcode' => '92121',
'country' => 'US'
);
// Now we create the order
$order = wc_create_order();
// The add_product() function below is located in /plugins/woocommerce/includes/abstracts/abstract_wc_order.php
$order->add_product( get_product( 99 ), 1); // Use the product IDs to add
// Set addresses
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
// Set payment gateway
$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method( $payment_gateways['bacs'] );
// Calculate totals
$order->calculate_totals();
$order->update_status( 'Completed', 'Order created dynamically - ', TRUE);
}
@fredichisar
Copy link

fredichisar commented Aug 30, 2017

Hi Rémi, is there any way to calculate and add shipping method / cost to an programmatically order ?
I've seen a method in the cart class file, by getting data from the session, but not in the order class...

The way I've tried is by adding "add_shipping" of "new WC_Shipping_Rate" to the $order, $taxes is set with an empty array but it's always adding taxes in shipping line...

As usually, very useful tips !!
Thx for your help ;)

@junaidakram96
Copy link

in which folder i should place this file??

@maartents
Copy link

Where do i need to add this and how do i call the function? sorry im a new coder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment