如何保存 woocommerce 产品元数据,然后将其发送到客户电子邮件中?

How to save woocommerce product meta data and then send it in customer email?

折腾了两天,现在在这里分享我的问题。我想在插入产品时将会话值保存到产品的元字段中。目前我正在使用这个不起作用的代码

add_action( 'woocommerce_review_order_after_payment', 'save_product_status_discount', 10, 1 );

function save_product_status_discount($order, $sent_to_admin, $plain_text, $email){
    $order_data = $order->get_data(); 
    $item_data = $item_obj->get_data();
    $my_post_meta1 = get_post_meta($item_data['order_id'], 'status_discount'.$item_data['order_id'], true);
     if(empty ( $my_post_meta1 )){
    update_post_meta($item_data['order_id'],'status_discount'.$item_data['order_id'],$_SESSION['status_discount_price']);

     }

}

请帮我看看我该怎么做。谢谢

您可以使用它,但效果不佳,因为您需要为每个订单商品执行此操作(我认为正确的方法在最后):

// Save the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'save_product_status_discount', 10, 1 );
function save_product_status_discount( $order_id ) {
    $status_discount = get_post_meta($order_id, 'status_discount'.$order_id, true);
    if(empty ( $status_discount ) && ! empty( $_SESSION['status_discount_price'] ) )
        update_post_meta( $order_id, 'status_discount'.$order_id, $_SESSION['status_discount_price'] );
    }
}

// Display the order meta with field value
add_action( 'woocommerce_review_order_after_payment', 'display_product_status_discount', 10, 4 );
function save_product_status_discount($order, $sent_to_admin, $plain_text, $email){
    $status_discount = get_post_meta($order_id, 'status_discount'.$order_id, true);
    if( ! empty ( $status_discount ) )
        echo '<p>'.__( 'Status discount', 'woocommerce' ) . ': ' . $status_discount . '</p>
}

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

The correct way to do it, is to incorporate this "status discount" as item ID meta data, because you can have many items in an order.

所以最好的选择和工作代码应该只是那个紧凑的函数:

// Save the order item meta data with custom field value and display it as order items meta data
add_action('woocommerce_add_order_item_meta','save_product_status_discount', 1, 3 );
function save_product_status_discount( $item_id, $values, $cart_item_key ) {
    if( empty( $_SESSION['status_discount_price'] ) )
        wc_add_order_item_meta( $item_id, 'Status discount', $_SESSION['status_discount_price'], true );
}

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

在 WooCommerce 3+ 中测试并有效。