仅为 WooCommerce 管理员电子邮件通知自定义订单项元

Customize order item meta only for WooCommerce admin email notifications

我需要添加自定义分类来管理新订单电子邮件,而不是客户电子邮件。我当前的代码显示了订单中每个项目的自定义分类法,但它同时出现在管理员和客户电子邮件中,这是我不想要的。

通过 email-order-items.php 查找,我没有看到在我正在使用的挂钩中利用 $sent_to_admin 的方法。我错过了什么吗?

如何仅使用挂钩和过滤器将我的自定义分类法添加到管理员电子邮件?

add_action( 'woocommerce_order_item_meta_end', 'custom_woocommerce_order_item_meta_end', 10, 3 );

function custom_woocommerce_order_item_meta_end( $item_id, $item, $order ) {
     $product = $item->get_product();

     $locations = get_the_terms( $product->get_id(), 'my_custom_taxonomy' );
     echo '<br/>';
     echo '<div style="margin-top: 20px;">';
     foreach( $locations as $location ) {
          echo 'Location:  <b>' . $location->name . '</b>';
          echo '<br/>';
     }
     echo '</div>
}

这可以使用 $GLOBAL 变量来完成。我也重新审视了你的代码。试试这个:

// Setting the "sent_to_admin" as a global variable
add_action('woocommerce_email_before_order_table', 'email_order_id_as_a_global', 1, 4);
function email_order_id_as_a_global($order, $sent_to_admin, $plain_text, $email){
    $GLOBALS['email_data'] = array(
        'sent_to_admin' => $sent_to_admin, // <== HERE we set "$sent_to_admin" value
        'email_id' => $email->id, // The email ID (to target specific email notification)
    );
}

// Conditionally customizing footer email text
add_action( 'woocommerce_order_item_meta_end', 'custom_email_order_item_meta_end', 10, 3 );
function custom_email_order_item_meta_end( $item_id, $item, $order ){

    // Getting the custom 'email_data' global variable
    $refNameGlobalsVar = $GLOBALS;
    $email_data = $refNameGlobalsVar['email_data'];

    // Only for admin email notifications
    if( ! ( is_array( $email_data ) && $email_data['sent_to_admin'] ) ) return;

    ## -------------------------- Your Code below -------------------------- ##

    $taxonomy = 'my_custom_taxonomy'; // <= Your custom taxonomy

    echo '<br/><div style="margin-top: 20px;">';
    foreach( get_the_terms( $item->get_product_id(), $taxonomy ) as $term )
        echo 'Location:  <b>' . $term->name . '</b><br/>';
    echo '</div>';
}

代码进入活动子主题(或活动主题)的 function.php 文件。

已测试并有效。