Last active
May 13, 2019 08:42
-
-
Save itzmekhokan/e2084ed7121537f01a6aaaf539e00da7 to your computer and use it in GitHub Desktop.
Create order dynamically in woocommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Create order dynamically | |
*/ | |
function create_order_dynamically() { | |
$customer_email = '[email protected]'; | |
$customer_address = array( | |
'first_name' => 'Peter', | |
'last_name' => 'Parker', | |
'company' => '', | |
'email' => $customer_email, | |
'phone' => '9876543210', | |
'address_1' => 'Queens', | |
'address_2' => '', | |
'city' => 'New York City', | |
'state' => 'New York', | |
'postcode' => '12345', | |
'country' => 'US' | |
); | |
$default_password = wp_generate_password(); | |
if (!$user = get_user_by('login', $customer_email)) $user = wp_create_user( $customer_email, $default_password, $customer_email ); | |
// Add your product as item products for order | |
$order_item = 12; // keep in mind these product must exists | |
$product = wc_get_product($order_item); | |
// get product's shipping class | |
$shipping_class = get_term_by('slug', $product->get_shipping_class(), 'product_shipping_class'); | |
WC()->shipping->load_shipping_methods(); | |
$shipping_methods = WC()->shipping->get_shipping_methods(); | |
$selected_shipping_method = $shipping_methods['free_shipping']; | |
$class_cost = $selected_shipping_method->get_option('class_cost_' . $shipping_class->term_id); | |
// Now create your order | |
$order = wc_create_order(array('customer_id' => $user->ID)); | |
$order->add_product( $product, $quantity = 1); | |
$order->set_address( $customer_address, 'billing' ); | |
$order->set_address( $customer_address, 'shipping' ); | |
$order->add_shipping((object)array ( | |
'id' => $selected_shipping_method->id, | |
'label' => $selected_shipping_method->title, | |
'cost' => (float)$class_cost, | |
'taxes' => array(), | |
'calc_tax' => 'per_order' | |
)); | |
$order->calculate_totals(); | |
$order->update_status("completed", 'Order dynamically created!', TRUE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment