Send a custom email when WooCommerce checkout button is pressed

烈酒焚心 提交于 2019-12-04 19:03:18

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 …

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!