4

我在 WooCommerce 中发送自定义电子邮件时遇到问题。

这是错误:

致命错误:无法
在第 548 行的 /home/wp-content/themes/structure/functions.php 中使用 WC_Order 类型的对象作为数组

除了标准的订单确认电子邮件之外,我的客户希望在每次客户订购和付款时发送自定义电子邮件。

这是我的代码:

$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' )

我也试过用"woocommerce_thankyou"钩子代替,"woocommerce_payment_complete"但还是不行。

我使用的 Wordpress 版本是 4.5.2,WooCommerce 版本是 2.6.1。

4

2 回答 2

2

可能存在以下问题:$order->billing_address;......所以我们可以有一个不同的方法来获取当前用户的电子邮件(不是计费或运输),使用wp_get_current_user();wordpress 功能。那么你的代码将是:

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

您可以在通过电子邮件wp_mail()替换功能之前进行测试,如下所示:$user_email

wp_mail('your.mail@your-domain.tld', 'subject', 'This is custom email', $headers );

如果您收到邮件,则问题来自$to_email = $order->billing_address;. (也可以用钩子
试试woocommerce_thankyou) 。

最后一件事,您必须在托管服务器上测试所有这些,而不是在您的计算机上使用 localhost。在大多数情况下,在本地主机上发送邮件不起作用……</p>

于 2016-06-18T02:35:09.813 回答
1

致命错误:无法在第 548 行的 /home/wp-content/themes/structure/functions.php 中使用 WC_Order 类型的对象作为数组

这意味着这$object是一个对象,您需要使用对象表示法,例如$object->billing_address代替数组表示法$object['billing_address']。帐单地址对象属性将在您通过类的魔术__get()方法调用时定义WC_Order,这与上面 LoicTheAztec 的方法没有太大区别。

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' );
于 2016-06-18T05:00:57.240 回答