根据发货和订单备注向 WooCommerce 客户完整订单电子邮件添加文本

Add a text to WooCommerce customer complete order email based on shipping and order note

我正在尝试根据运费和订单备注是否为空,将信息添加到客户完整的订单电子邮件中。

根据订单备注字段是否已填写,两种不同的消息。我已经下了测试订单,但没有任何显示。

这是我要开始工作的代码:

add_action( 'woocommerce_email_order_details', 'local_pickup_order_instructions', 10, 4 );
function local_pickup_order_instructions( $order, $sent_to_admin, $plain_text, $email ) {

    if ( 'customer_completed_order' != $email->id ) return;

    foreach( $order->get_items('shipping') as $shipping_item ) {

        $shipping_rate_id = $shipping_item->get_method_id();

        $method_array = explode(':', $shipping_rate_id );

        $shipping_method_id = reset($method_array);

    if ('local_pickup' == $shipping_method_id && empty($_POST['order_comments'])){ ?>

        <div style="">Your instructions text here</div>

    <?php

    break;
    }
        else {

    if ('local_pickup' == $shipping_method_id && !empty($_POST['order_comments'] ) ) { ?>

        <div style="">Your instructions text here</div>
    
        <?php

        }
    }
}
}

您的代码中有一些错误...如果有(或没有)客户备注,当送货方式为“本地取件”时要显示不同的自定义文本,请使用以下简化和重新访问的代码:

add_action( 'woocommerce_email_order_details', 'local_pickup_order_instructions', 10, 4 );
function local_pickup_order_instructions( $order, $sent_to_admin, $plain_text, $email ) {
    if ( $email->id === 'customer_completed_order' ) {
        $shipping_items = $order->get_items('shipping');
        $shipping_item  = reset($shipping_items); // Get first shipping item
        $customer_note  = $order->get_customer_note(); // Get customer note

        // Targeting Local pickup shipping methods
        if ( strpos( $shipping_item->get_method_id(), 'local_pickup' ) !== false ) {
            if ( empty($customer_note) ) {
                echo '<div style="color:red;">'.__("Instructions text here… (No customer note)").'</div>'; // Empty order note
            } else {
                echo '<div style="color:green;">'.__("Instructions text here… (has a customer note)").'</div>'; // Filled order note
            }
        }
    }
}

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