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>' . "rn";
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) withwp_get_current_user();
wordpress function. Then your code will be: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…
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 theWC_Order
class, which really isn’t very different from LoicTheAztec’s approach above.