在 Woocommerce 电子邮件主题中显示订单项的产品属性值

Display product attribute value from order item in Woocommerce email subject

在 woocommerce 中,我试图获取特定的产品属性值并将其显示在管理员新订单电子邮件通知的主题行中。

我找到了以下代码,但我对它的工作知之甚少:

add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2);
function change_admin_email_subject( $subject, $order ) {

    global $woocommerce;
    global $product;       
    {
        $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
        $subject = sprintf( '[%s] New customer order (# %s) from %s %s',
                               $blogname, $order->id,
                               $order->billing_first_name, $order->billing_last_name );
    } 
    return $subject;
}

我也尝试了这个 (其中 xxxxx 是我的属性的一部分):

add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2);
function change_admin_email_subject( $subject, $order ) {

    global $woocommerce;
    global $product;       
    {  
        $pa_xxxxx_value = get_order_meta($order->id, 'pa_xxxxx', true);
        $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
        $subject = sprintf( '[%s] [%s] New customer order (# %s) from %s %s',
                              $pa_xxxxx_value, $blogname, $order->id,
                              $order->billing_first_name, $order->billing_last_name );
    } 
    return $subject;
}

但是他们两个都不行。

如何从 Woocommerce 电子邮件主题中的订单项获取和显示特定产品属性值?

订单可以包含很多商品,自 Woocommerce 3 以来您的代码中存在一些错误。

下面的代码将在订单项中搜索特定产品属性(分类法),如果找到,它将显示具有此产品属性术语名称值的新自定义主题:

add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2);
function change_admin_email_subject( $subject, $order ) {
    // HERE define the product attribute taxonomy (start always with "pa_")
    $taxonomy = 'pa_color'; //

    // Loop through order items searching for the product attribute defined taxonomy
    foreach( $order->get_items() as $item ){
        // If product attribute is found
        if( $item->get_meta($taxonomy) ){
            // Custom new subject including the product attribute term name
            $subject = sprintf( '[%s] [%s] New customer order (# %s) from %s %s',
                get_term_by('slug', $item->get_meta($taxonomy), $taxonomy )->name, // Term name
                wp_specialchars_decode(get_option('blogname'), ENT_QUOTES),
                $order->get_id(),
                $order->get_billing_first_name(),
                $order->get_billing_last_name()
            );
            break; // Stop the loop
        }
    }

    return $subject;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。