A Strange Workaround to an Enigmatic Issue (Woocommerce’s Order Emails)

UPDATE: The root cause of this issue eventually turned out to be a database issue, with orders being set to a status of ‘pending-2′ rather than ‘pending’ by default, due to a conflict with another plugin. For my solution, take a look at this post.

Recently I have been struggling with Woocommerce’s problematic system of automatically sending out e-mails related to orders. Specifically, what should be happening is whenever an order is placed, a receipt should be sent to the customer, and a new-order notification should be sent to the admin. When an order is marked as completed, another email should be sent to the customer informing them of this and allowing them to download their products (if applicable).

None of these emails were being sent from my client’s website. I checked the site against spam blacklists — everything looked good. The MX records were set up properly. WordPress’s wp_mail() function was working properly. Email was working perfectly well other than these specific Woocommerce emails.

(Side note: an amusing and informative article I found along the way)

In the end I deduced that deep in the Moria-like abyss of Woocommerce, the Woo-dwarf in charge of sending e-mails had died. I have no idea why he or she bit the dust; I only know that I was able to use Woocommerce’s built-in mailer to send the order e-mails out myself, manually, and I was unable to locate the code in Woocommerce that should have been sending them out in the first place.

As frustrating as it is to not find out the root cause of the problem, I was able to come up with a solution. This simple workaround can be pasted into your functions.php file if you’re having a similar problem. It might work for you, it might not, but it worked for my client:

// Workaround for the mysterious bug in Woocommerce that prevents order emails
// from being sent.

add_action( 'woocommerce_thankyou', 'order_email_workaround' );

function order_email_workaround ($order_id) {
    global $woocommerce;
    $mailer = $woocommerce->mailer();
    // Email customer with order-processing receipt
    $email = $mailer->emails['WC_Email_Customer_Processing_Order'];
    $email->trigger( $order_id );
    // Email admin with new order email
    $email = $mailer->emails['WC_Email_New_Order'];
    $email->trigger( $order_id );
}

add_action( 'woocommerce_payment_complete', 'order_complete_email_workaround' );

function order_complete_email_workaround ($order_id) {
    global $woocommerce;
    $mailer = $woocommerce->mailer();
    $email = $mailer->emails['WC_Email_Customer_Completed_order'];
    $email->trigger( $order_id );
}