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.
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 withwoocommerce_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' );
来源:https://stackoverflow.com/questions/37891182/custom-email-is-not-sending-on-order-complete-in-woocommerce