2017-08-21 29 views
1

掙扎了兩天後,我現在在這裏分享我的問題。我想在產品插入時將會話值保存到產品的元字段中。目前我使用的代碼不起作用如何保存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']); 

    } 

} 

請幫我該怎麼做。感謝

回答

0

你可以使用,但不會正常工作,你應該需要做的是爲每個訂單項目(我認爲,正確的做法是低於結束)

// 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文件中,或者也存在於任何插件文件中。

正確的方式做到這一點,是將這一「地位打折」作爲項目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); 
} 

代碼放在您的活動子主題(或主題)的function.php文件或也以任何插件文件。

在WooCommerce 3+中測試並正常工作。

相關問題