Muhammad Haris Muhammad Haris - 2 months ago 13
PHP Question

Custom Email is not sending on Order complete in WooCommerce

I am facing a problem to send a custom email in WooCommerce.

Here is Error:


Fatal error: Cannot use object of type WC_Order as array in

/home/wp-content/themes/structure/functions.php on line 548


My client want to send a custom email when everytime customer order and pay, besides the standard order confirmation email.

Here is my code:

$order = new WC_Order( $order_id );

function order_completed( $order_id ) {
$order = new WC_Order( $order_id );
$to_email = $order["billing_address"];
$headers = 'From: Your Name <your@email.com>' . "\r\n";
wp_mail($to_email, 'subject', 'This is custom email', $headers );

}

add_action( 'woocommerce_payment_complete', 'order_completed' )


I also tried
"woocommerce_thankyou"
hook instead of
"woocommerce_payment_complete"
but is still not working.

I use Wordpress version is 4.5.2 and WooCommerce version is 2.6.1.

Answer

Update2 (Related to the comments)

May be there is a problem with: $order->billing_address;… So we can have a different approach getting the current user email (not billing or shipping) with wp_get_current_user(); wordpress function. Then your code will be:

add_action( 'woocommerce_payment_complete', 'order_completed' )
function order_completed( $order_id ) {
    $current_user = wp_get_current_user();
    $user_email = $current_user->user_email;
    $to = sanitize_email( $user_email );
    $headers = 'From: Your Name <your@email.com>' . "\r\n";
    wp_mail($to, 'subject', 'This is custom email', $headers );
}

You can test before wp_mail() function replacing $user_email by your email like this:

wp_mail('your.mail@your-domain.tld', 'subject', 'This is custom email', $headers );

If you get the mail, the problem was coming from $to_email = $order->billing_address;.
(Try it also with woocommerce_thankyou hook too).

Last thing, you have to test all this on a hosted server, not with localhost on your computer. On localhost sending mails doesn't work in most cases…