Skip to content

Instantly share code, notes, and snippets.

@truongluu
Forked from shitpoet/create_order.php
Created November 11, 2023 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save truongluu/111de7c92b5c4f3bffc99ac96d216252 to your computer and use it in GitHub Desktop.
Save truongluu/111de7c92b5c4f3bffc99ac96d216252 to your computer and use it in GitHub Desktop.
Programmatically create order, add (variative) products from cart to it, change status to `processing` and empty cart. Wordpress, WooCommerce 2.4.
$address = array(
'first_name' => $customer_name,
'last_name' => '',
'company' => '',
'email' => $customer_email,
'phone' => $customer_phone,
'address_1' => '',
'address_2' => '',
'city' => '',
'state' => '',
'postcode' => '',
'country' => ''
);
$order = wc_create_order();
// add products from cart to order
$items = WC()->cart->get_cart();
foreach($items as $item => $values) {
$product_id = $values['product_id'];
$product = wc_get_product($product_id);
$var_id = $values['variation_id'];
$var_slug = $values['variation']['attribute_pa_weight'];
$quantity = (int)$values['quantity'];
$variationsArray = array();
$variationsArray['variation'] = array(
'pa_weight' => $var_slug
);
$var_product = new WC_Product_Variation($var_id);
$order->add_product($var_product, $quantity, $variationsArray);
}
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->calculate_totals();
$order->update_status( 'processing' );
WC()->cart->empty_cart();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment