问题
I am trying to send a custom email whenever the checkout button is pressed for Woocommerce using PHP.
This email will be sent alongside with the email notifications of wooCommerce. I have used this answer, and edited the code like:
//execute some php on successfull checkout
add_action( 'woocommerce_payment_complete', 'so_32512552_payment_complete' );
function so_32512552_payment_complete( $order_id ){
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item ) {
if ( $item['product_id'] > 0 ) {
$_product = $order->get_product_from_item( $item );
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("info@example.com","My subject",$msg);
}
}
}
But nothing seems to happen. Any ideas?
Thanks
回答1:
This doesn't work because this hook is fired only when the order status is completed …
Also is better to use wp_mail()
than mail()
function.
Instead you could try to use a custom function hooked in woocommerce_thankyou
action hook:
add_action( 'woocommerce_thankyou', 'custom_email_notification', 10, 1 );
function custom_email_notification( $order_id ) {
if ( ! $order_id ) return;
## THE ORDER DATA ##
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Iterating through each order items
foreach ( $order->get_items() as $item_id => $order_item ) {
// Accessing to the protected data of the WC_Order_Item_Product object
$order_item_data = $order_item->get_data();
// Get the associated WC_Product object
$product = $order_item->get_product();
// Accessing to the WC_Product object protected data
$product_data = $product->get_data();
}
## SENDING AN EMAIL (outside the loop is better to send it once) ##
$to = "test@mail.com";
$subject = "the subject here";
$content = "Here goes your message";
// Sending your custom email notification
wp_mail( $to, $subject, $content );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested on WooCommerce 3+ and works.
The
woocommerce_thankyou
hook is triggered in order-received page …
来源:https://stackoverflow.com/questions/45267781/send-a-custom-email-when-woocommerce-checkout-button-is-pressed