Skip to content

Instantly share code, notes, and snippets.

@shitpoet
Created December 3, 2015 19:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save shitpoet/34d756aa8d07b44bdeb8 to your computer and use it in GitHub Desktop.
Save shitpoet/34d756aa8d07b44bdeb8 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();
@insafm
Copy link

insafm commented Jan 2, 2018

Got error like

Fatal error: Uncaught Error: Call to a member function empty_cart() on null in /var/www/html/live/something....................;

Any solution?

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