I'm looking for a way to create a WC order programmatically for a subsite in my multisite environment.

When I use the following, the order is created on the main site and not the subsite with ID 7:

switch_to_blog( 7 );

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

// Get orderid from order-to-be-made
$neworderid = trim( str_replace( '#', '', $bestelling->get_order_number() ) );

// Get product data
$occurences = $_POST['productids'];

foreach($occurences as $key => $value) {
  // Add products
  $product = wc_get_product($key);
  $bestelling->add_product($product, $value);

// Set addresses
$bestelling->set_address( $billingaddress, 'billing' );
$bestelling->set_address( $shippingaddress, 'shipping' );

// Set payment gateway
$payment_gateways = WC()->payment_gateways->payment_gateways();
$bestelling->set_payment_method( $payment_gateways['bacs'] );

$bestelling->set_customer_note( $_POST['customer_message'] );

// Calculate totals

// Give Revamp status
$bestelling->update_status('revamped', 'This order has been made with the revamp tool.', TRUE);

do_action( 'woocommerce_checkout_order_processed', $neworderid );


Can it be done this way or should I look at this from another angle? Thanks in advance :).

  • I dug into wc_create_order and WC_Order, and as far as I can tell it just runs wp_insert_post(), which should create the order on the correct site when switch_to_blog is used. So what you've got should be fine. The part that's missing is the context under which this code is running. Where does your code run? – Jacob Peattie Feb 18 at 13:56
  • Thanks for your reply! The fact that I couldn't find anything about this suggests that it should work I guess. I made a page template where all information for a new order can be entered. Then I used a PHP include like this to include a php file where the code from above is: if (isset($_POST['revamp2']) ){ include 'revamp3.php'; } I placed this code just below get_header(); – Pim Feb 18 at 14:32
  • Any thoughts on why this still won't work now you know where I run this code? – Pim Feb 21 at 14:56
  • Okay, instead of using an include, I've tried placing the "create_order" code on the bottom of the page template and this does work. Still don't know why this would make a difference but my problem is solved. – Pim Feb 25 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.