Problem with woocommerce_add_order_item_meta

假如想象 提交于 2019-12-24 09:04:11

问题


i have spent the last 3 hours trying to fix a problem with a woocommerce deprecated hook and i'm going crazy because i have tried hundred different options to make it work, and it's not happening.

This is the actual code, it suppose to save the value of custom fields. Any idea about how to make it work with a non obsolete hook?

add_action('woocommerce_add_order_item_meta','save_in_order_item_meta', 10, 3 );
function save_in_order_item_meta( $item_id, $values, $cart_item_key ) {
if( isset( $values['custom_data'] ) ) {
   woocommerce_new_order_item( $item_id, $values['custom_data']['label'], $values['custom_data']['value'] );
}
}

Any help is welcome. Thank you

Edit; Already tried.

 add_action( 'woocommerce_add_order_item_meta', 'custom_add_order_item_meta', 20, 3 ); function custom_add_order_item_meta( 
 $item_id, $values, $cart_item_key ) { // Get cart item custom data and update order item meta if( isset( $values['custom_data'] ) ) { 
 wc_add_order_item_meta( $item_id, $values['custom_data']['label'], $values['custom_data']['value'] ); } }

 add_action( 'woocommerce_add_order_item_meta', 'custom_add_order_item_meta', 20, 3 );
 function custom_add_order_item_meta( $item_id, $values, $cart_item_key ) {
 $custom_field_value = $custom_field_value;

 if ( ! empty( $custom_field_value ) ){
    wc_add_order_item_meta( $item_id, $values['custom_data']['label'], $values['custom_data']['value']  );
}

}

回答1:


Hook woocommerce_add_order_item_meta is replaced by woocommerce_checkout_create_order_line_item, so with your code (assuming that the cart object contains your custom cart item data):

add_action('woocommerce_checkout_create_order_line_item', 'save_custom_order_item_meta_data', 10, 4 );
function save_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {
    if( isset( $values['custom_data']['label'] ) && isset( $values['custom_data']['value'] ) ) {
       $item->update_meta_data( $values['custom_data']['label'], $values['custom_data']['value'] );
    }
}

Code goes in function.php file of your active child theme (or active theme). It should works.

Related:

  • Replace woocommerce_add_order_item_meta hook in Woocommerce 3.4
  • Woocommerce: Which hook to replace deprecated "woocommerce_add_order_item_meta"
  • Threads with: woocommerce_checkout_create_order_line_item action hook


来源:https://stackoverflow.com/questions/53697569/problem-with-woocommerce-add-order-item-meta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!