Skip to content

Instantly share code, notes, and snippets.

@sayedulsayem
Created March 24, 2024 20:09
Show Gist options
  • Save sayedulsayem/9f00376372f75281acbc7a3fb77df061 to your computer and use it in GitHub Desktop.
Save sayedulsayem/9f00376372f75281acbc7a3fb77df061 to your computer and use it in GitHub Desktop.
WC (WooCommerce) order creating with Ajax. Trigger order mail included
/**
 * Creating order by clicking "One click order/ Ajax Order"
 *
 */
function sayedul_sayem_ajax_create_order() {
	$nonce = isset($_REQUEST['nonce']) ? $_REQUEST['nonce'] : '';
	$note = isset($_REQUEST['note']) ? sanitize_text_field($_REQUEST['note']) : null;

	if (!wp_verify_nonce($nonce, 'sayedul_sayem_nonce')) {
		wp_send_json_error('Unauthorized request');
	}

	$address = sayedul_sayem_get_customer_address();

	$cart = WC()->cart;

	$args = array(
		'status' => 'pending', // 'checkout-draft', 'processing', 'on-hold', 'completed', etc
		'customer_id' => get_current_user_id(), // null for guest checkout
		'customer_note' => $note,
		'created_via' => 'ajax',
		'cart_hash' => $cart->get_cart_hash(),
	);

	$order = wc_create_order($args);

	// set address
	$order->set_address($address, 'billing');
	$order->set_address($address, 'shipping');

	// set payment method
	$order->set_payment_method('cod');
	$order->set_payment_method_title('Cash On Delivery');

	foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
		$product_id = $cart_item['product_id'];
		$variation = isset($cart_item['variation']) ? $cart_item['variation'] : [];
		$variation_id = isset($cart_item['variation_id']) ? $cart_item['variation_id'] : 0;
		$quantity = $cart_item['quantity'];

		// custom meta
		$note = isset($cart_item['note']) ? $cart_item['note'] : '';

		if ($variation_id != 0) {
			// add variation product
			$product = new WC_Product_Variation($variation_id);
			$order_item_id = $order->add_product($product, $quantity, $variation);
		} else {
			// add simple product
			$product = wc_get_product($product_id);
			$order_item_id = $order->add_product($product, $quantity);
		}

		$order_item = $order->get_item($order_item_id);

		if (!empty($note)) {
			$order_item->update_meta_data('note', $note);
		}

		$order_item->save();
	}

	// shipping method add
	$shipping = new WC_Order_Item_Shipping();
	$shipping->set_method_title('Free shipping');
	$shipping->set_method_id('free_shipping:1');

	// calculate totals
	$order->calculate_totals();
	// for creating order with zero price
	// $shipping->set_total(0);
	$order->add_item($shipping);

	$order->save();

	// Send message to client
	$mailer = WC()->mailer()->get_emails();
	$mailer['WC_Email_Customer_Completed_Order']->trigger($order->id);

	// Send message to admin
	$mailer['WC_Email_New_Order']->trigger($order->id);

	// create the current cart
	$cart->empty_cart();

	$order_received_url = $order->get_checkout_order_received_url();

	wp_send_json_success($order_received_url);
}

/**
 * Get custom address
 *
 */
function sayedul_sayem_get_customer_address() {
	$address = array(
		'first_name' => '',
		'last_name'  => '',
		'company'    => '',
		'email'      => '',
		'phone'      => '',
		'address_1'  => '',
		'address_2'  => '',
		'city'       => '',
		'state'      => '',
		'postcode'   => '',
		'country'    => ''
	);

	if (is_user_logged_in()) {
		$current_user_id = get_current_user_id();
		$email = get_user_meta($current_user_id, 'billing_email', true);
		$fname = get_user_meta($current_user_id, 'billing_first_name', true);
		$lname = get_user_meta($current_user_id, 'billing_last_name', true);

		$address['first_name'] = !empty($fname) ? $fname : get_user_meta($current_user_id, 'first_name', true);
		$address['last_name']  = !empty($lname) ? $lname : get_user_meta($current_user_id, 'last_name', true);
		$address['company']    = get_user_meta($current_user_id, 'billing_company', true);
		$address['email']      = !empty($email) ? $email : get_user_meta($current_user_id, 'email', true);
		$address['phone']      = get_user_meta($current_user_id, 'billing_phone', true);
		$address['address_1']  = get_user_meta($current_user_id, 'billing_address_1', true);
		$address['address_2']  = get_user_meta($current_user_id, 'billing_address_2', true);
		$address['city']       = get_user_meta($current_user_id, 'billing_city', true);
		$address['state']      = get_user_meta($current_user_id, 'billing_state', true);
		$address['postcode']   = get_user_meta($current_user_id, 'billing_postcode', true);
		$address['country']    = get_user_meta($current_user_id, 'billing_country', true);
	} else {
		$address['first_name'] = isset($_REQUEST['billing_first_name']) ? sanitize_text_field($_REQUEST['billing_first_name']) : '';
		$address['last_name']  = isset($_REQUEST['billing_last_name']) ? sanitize_text_field($_REQUEST['billing_last_name']) : '';
		$address['company']    = isset($_REQUEST['billing_company']) ? sanitize_text_field($_REQUEST['billing_company']) : '';
		$address['email']      = isset($_REQUEST['billing_email']) ? sanitize_text_field($_REQUEST['billing_email']) : '';
		$address['phone']      = isset($_REQUEST['billing_phone']) ? sanitize_text_field($_REQUEST['billing_phone']) : '';
		$address['address_1']  = isset($_REQUEST['billing_address_1']) ? sanitize_text_field($_REQUEST['billing_address_1']) : '';
		$address['address_2']  = isset($_REQUEST['billing_address_2']) ? sanitize_text_field($_REQUEST['billing_address_2']) : '';
		$address['city']       = isset($_REQUEST['billing_city']) ? sanitize_text_field($_REQUEST['billing_city']) : '';
		$address['state']      = isset($_REQUEST['billing_state']) ? sanitize_text_field($_REQUEST['billing_state']) : '';
		$address['postcode']   = isset($_REQUEST['billing_postcode']) ? sanitize_text_field($_REQUEST['billing_postcode']) : '';
		$address['country']    = isset($_REQUEST['billing_country']) ? sanitize_text_field($_REQUEST['billing_country']) : '';
	}

	return $address;
}

/**
 * add custom field for each cart product
 */
add_filter('woocommerce_add_cart_item_data', 'sayedul_sayem_add_cart_item_data', 10, 3);
function sayedul_sayem_add_cart_item_data($cart_item_data, $product_id, $variation_id) {
	if (isset($_REQUEST['note'])) {
		$cart_item_data['note'] = sanitize_text_field($_REQUEST['note']);
	}
	return $cart_item_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment