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



经过两天的挣扎,现在在这里分享我的问题。我想在插入产品时将会话值保存到产品的元字段中。目前我正在使用此代码

不起作用
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>
}

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

正确的方法是将此"状态折扣"合并为商品ID元数据,因为一个订单中可以有很多商品。

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

// 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 );
}

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

在WooCommerce 3+中测试并工作。

最新更新