编程语言
首页 > 编程语言> > php – 按下WooCommerce结帐按钮时发送自定义电子邮件

php – 按下WooCommerce结帐按钮时发送自定义电子邮件

作者:互联网

我正在尝试使用PHP按下Woocommerce的结帐按钮时发送自定义电子邮件.

此电子邮件将与wooCommerce的电子邮件通知一起发送.
我使用过这个answer,编辑代码如下:

//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);


        }
    }
}

但似乎没有任何事情发生.有任何想法吗?

谢谢

解决方法:

这不起作用,因为只有在订单状态完成时才会触发此挂钩…
使用wp_mail()也比使用mail()函数更好.

相反,您可以尝试使用挂钩在woocommerce_thankyou动作钩子中的自定义函数:

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 );
}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

此代码在WooCommerce 3上进行测试并正常运行.

The woocommerce_thankyou hook is triggered in order-received page …

标签:checkout,php,wordpress,woocommerce,email-notifications
来源: https://codeday.me/bug/20191007/1864889.html