如何根据自定义订单元编辑订单电子邮件内容?

问题描述 投票:0回答:1

对于 WooCommerce 订单,在创建新订单时,我添加了一个名为

order_approved
的自定义字段(自定义元数据)。现在我想根据该元数据在电子邮件通知上添加自定义文本。 但是,我在订单对象上看不到这个自定义元数据。

add_action('woocommerce_thankyou', 'assign_approver_to_order');
function assign_approver_to_order($order_id){
    $user_id = get_current_user_id();
    $company_id = get_user_meta($user_id, 'parent', true);

    if($company_id){
        update_post_meta($order_id, 'approval_required', 'yes');
    }   
}


add_action( 'woocommerce_email_order_details', 'custom_text_in_customer_new_order_email', 999, 4 );
function custom_text_in_customer_new_order_email( $order, $sent_to_admin, $plain_text, $email ) {
    $order_approval = get_post_meta($order->id, 'approval_required', true);
    echo "order approval: ".$order_approval ."<br>"; // I am not getting any value

    var_dump($order)// also could not see the 'approval_required' order meta on the order object

    if( $order_approval == "yes" ) {
        switch($email->id){
            case "new_order":
                $custom_txt = "<b>This order is waiting for approval.</b><br>";
                echo  $custom_txt;
                break;
            case "customer_on_hold_order":
                $custom_txt = "<b>Your order is waiting for approval.</b><br>";
                echo  $custom_txt;
                break;
        }
    }
}
php wordpress woocommerce hook-woocommerce
1个回答
0
投票

您的代码中存在一些错误,并且您没有为第一个函数使用正确的钩子…从 WooCommerce 3 开始,您不应该再使用任何 WordPress post 元函数,而是应该在 WC_Order 等 CRUD 对象上使用 getter 和 setter 方法对象。如果启用了高性能订单存储,这是强制性的,因为 WooCommerce 正在逐步将数据迁移到自定义表。

假设“父”用户元数据存在,请尝试以下操作:

add_action('woocommerce_checkout_order_created', 'assign_approver_to_order');
function assign_approver_to_order($order){
    if( get_user_meta($order->get_user_id(), 'parent', true) ){
        $order->update_meta_data('approval_required', 'yes');
        $order->save();
    }   
}


add_action( 'woocommerce_email_order_details', 'custom_text_in_customer_new_order_email', 100, 4 );
function custom_text_in_customer_new_order_email( $order, $sent_to_admin, $plain_text, $email ) {
    if( $order->get_meta('approval_required') === "yes" ) {
        switch($email->id){
            case "new_order":
                $custom_txt = "<b>This order is waiting for approval.</b><br>";
                echo  $custom_txt;
                break;
            case "customer_on_hold_order":
                $custom_txt = "<b>Your order is waiting for approval.</b><br>";
                echo  $custom_txt;
                break;
        }
    }
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.