Custom Email is not sending on Order complete in WooCommerce

我怕爱的太早我们不能终老 提交于 2019-12-05 18:05:55

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_custom_email_notification' )
function order_completed_custom_email_notification( $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…

Fatal error: Cannot use object of type WC_Order as array in /home/wp-content/themes/structure/functions.php on line 548

This means that $object is an object and you need to use object notation such as $object->billing_address instead of array notation $object['billing_address']. The billing address object property will be defined when you call it by the magic __get() method of the WC_Order class, which really isn't very different from LoicTheAztec's approach above.

function order_completed( $order_id ) {
    $order = wc_get_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' );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!