添加来自 wc 字段工厂的电子邮件收件人以获取 woocommerce 电子邮件通知

Add email recipients from wc field factory for woocommerce email notification

我正在使用 woocommerce 销售课程产品。该课程使用 wc 字段工厂来为学生姓名和学生电子邮件地址自定义产品字段。学生电子邮件地址的字段名称是 "student_email"。然后我尝试从该字段(电子邮件地址)中获取值,并在购买此产品时将其用作来自 woocommerce 的电子邮件的收件人。

输入的值确实显示在购物车页面、订单收据电子邮件等上。我设置的自定义电子邮件模板确实有效(它目前发送到管理员电子邮件,直到我让它工作)。但我不知道如何获取学生电子邮件地址值以用作收件人。

我尝试了几种方法,包括以下内容:

$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
// Get "student email" custom field value
$student_emails = get_post_meta($order_id, "wccpf_student_email", true );
$this->recipient = $student_emails;

function custom_add_to_cart_action_handler($_cart_item_data, $_product_id) {
if(isset($_cart_item_data[“wccpf_student_email”])) {
$value = $_cart_item_data[“wccpf_student_email”];
return $value;
}
}
add_filter(‘woocommerce_add_cart_item_data’, array( $this, ‘custom_add_to_cart_action_handler’ ), 100, 2);
$this->recipient = $value;

这是在我的自定义电子邮件 class php 文件中完成的。但是似乎没有什么可以获取 student_email 自定义产品字段的值。任何帮助将不胜感激!

代码已更新

由于您的“student_email”自定义字段是在产品页面上设置的,因此它被保存为订单项元数据(而不是订单元数据),并带有您为其设置的标签名称……
所以元键应该是 "Student email" (the label name) 你需要遍历订单项来获取这些电子邮件值(如果订单有多个项目。

下面的代码将获取这些电子邮件(如果存在)并将主题添加到电子邮件收件人以用于订单“正在处理”和“已完成”的电子邮件通知:

add_filter( 'woocommerce_email_recipient_customer_processing_order', 'student_email_notification', 10, 2 );
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'student_email_notification', 10, 2 );
function student_email_notification( $recipient, $order ) {
    if ( ! is_a( $order, 'WC_Order' ) ) return $recipient;

    $student_emails = array();
    
    // Loop though  Order IDs
    foreach( $order->get_items() as $item_id => $item ){
        // Get the student email
        $student_email = wc_get_order_item_meta( $item_id, 'Student email', true );
        if( ! empty($student_email) )
            $student_emails[] = $student_email; // Add email to the array
    }
    
    // If any student email exist we add it
    if( count($student_emails) > 0 ){
        // Remove duplicates (if there is any)
        $student_emails = array_unique($student_emails);
        // Add the emails to existing recipients
        $recipient .= ',' . implode( ',', $student_emails );
    }
    return $recipient;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。现在已经过测试并且可以使用。