Create programmatically a “completed” order without sending email to customer in WooCommerce

Rate this post

I use this code for new order and set complete status.

After it, woocommerce send automatic email to buyer.

But I want dont send this email.

How I can?

$order = wc_create_order();

foreach($_POST['basket'] as $prod){
    $order->add_product(get_product($prod['id']), $prod['count']);

$order->set_address($address, 'billing');
$order->update_status("completed", 'TEST', TRUE);

Note: I dont want disable send email from wp-admin



Note that the function get_product() is obsolete and replaced by wc_get_product() instead.

To avoid notifications to customer, you can set user ID to 0 first, then after updating order status to “complete”, you can set the user address and the real user ID as follows:

$order = wc_create_order();

foreach($_POST['basket'] as $prod){
    $order->add_product( wc_get_product($prod['id']), $prod['count']);

$order->update_status("completed", 'TEST', TRUE);

$order->set_address($address, 'billing'); // set address
$order->set_customer_id($userId); // Set user ID
$order_id = $order->save(); // Save to database (get order ID)

// Allow resending new order email
add_filter('woocommerce_new_order_email_allows_resend', '__return_true' );

// Resend new order email
WC()->mailer()->get_emails()['WC_Email_New_Order']->trigger( $order_id );

// Disable resending new order email
add_filter('woocommerce_new_order_email_allows_resend', '__return_false' );

Tested and works.

The only thing is that you will get 2 times “New order” notification sent to the admin (The second email will be set with the correct customer address details).

Leave a Reply

Your email address will not be published.

Back to top button