【问题标题】:Get a custom fields value to be displayed in Woocommerce email notifications获取要在 Woocommerce 电子邮件通知中显示的自定义字段值
【发布时间】:2017-11-07 20:41:01
【问题描述】:

我使用 WC 字段工厂生成了一些自定义字段,包括一个名为“message_to_recipient”的文本框。我想将此传递给发出的电子邮件。

在我的functions.php中,我使用的是这个:

add_action( 'woocommerce_email_before_order_table', 'add_order_email_instructions', 10, 2 );

function add_order_email_instructions( $order, $sent_to_admin ) {

 $custom_message = get_post_meta( $order->ID, "message_to_recipient", true );

 if ( ! $sent_to_admin ) {

 echo '<h2>You received a gift Card from '.$order->billing_first_name .' '.$order->billing_last_name.'</h2>';
 echo '<p><strong>Message:</strong> ' . $custom_message. '</p>'; 

}

第一个回声,调用$order-&gt;billing_first_name 等工作正常。但第二个没有。

使用过 WC Field Factory,我只是没有使用正确的名称,还是这是从订单中获取元数据的错误钩子?

【问题讨论】:

    标签: php wordpress woocommerce orders email-notifications


    【解决方案1】:

    要从 WC_Order 对象中获取订单 ID,因为 WooCommerce 版本 3+,您应该需要使用 get_id() 方法。

    另外你最好使用WC_Order方法作为get_billing_last_name()get_billing_last_name()来代替......

    所以你的代码应该是:

    add_action( 'woocommerce_email_before_order_table', 'add_order_email_instructions', 10, 2 );
    function add_order_email_instructions( $order, $sent_to_admin ) {
        if ( ! $sent_to_admin ) {
            // compatibility with WC +3
            $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
            $first_name = method_exists( $order, 'get_billing_first_name' ) ? $order->get_billing_first_name() : $order->billing_first_name;
            $last_name = method_exists( $order, 'get_billing_last_name' ) ? $order->get_billing_last_name() : $order->billing_last_name;
    
            $custom_message = get_post_meta( $order_id , "message_to_recipient", true );
    
            echo '<h2>You received a gift Card from '. $first_name .' '. $last_name .'</h2>';
    
            if( ! empty($custom_message) )
                echo '<p><strong>Message:</strong> ' . $custom_message. '</p>'; 
        } 
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    这应该适合你了(在 WC 2.5+ 以后的任何 WC 版本上)...


    订单相关贴:How to get WooCommerce order details

    【讨论】:

    • 谢谢。我必须使用错误的字段名称。这段代码的其余部分,以及更新的方法,都可以工作。
    • 我将 get_post_meta 函数中的 key 参数替换为其他内容,代码有效,只是键名“message_to_recipient 一定是错误的”
    猜你喜欢
    • 2019-01-13
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2020-11-05
    • 2020-09-09
    • 2018-08-30
    • 2021-02-01
    相关资源
    最近更新 更多