【问题标题】:Customize order item meta only for WooCommerce admin email notifications仅为 WooCommerce 管理员电子邮件通知自定义订单项元
【发布时间】:2018-06-28 07:55:36
【问题描述】:

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

查看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>
}

【问题讨论】:

    标签: php wordpress woocommerce orders email-notifications


    【解决方案1】:

    这可以使用$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 文件中。

    经过测试并且有效。

    【讨论】:

    • 抱歉耽搁了!从来没想过要走那条路。起初我有点犹豫,所有关于在 Wordpress 中使用 Globals 的坏消息是什么,但它就像一个冠军。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 2020-11-26
    • 2018-04-23
    • 2021-09-05
    • 2016-03-03
    • 2021-12-13
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多