1

I'm having trouble adding custom order item meta data. I have found one way to do it, but it looks terrible. enter image description here

The code:

add_action('woocommerce_add_order_item_meta',  'func_add_custom_data_to_order_item_meta',1,2);
function func_add_custom_data_to_order_item_meta( $item_id, $values ) {
    global $woocommerce,$wpdb;

    if(!empty($values['custom'])){
        $custom_order_meta = $values['custom'];
        wc_add_order_item_meta($item_id, 'custom', serialize($custom_order_meta));
    }
}

Is there any way to iterate through the key value pairs and get their contents on a new line each time?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Paudun
  • 287
  • 1
  • 6
  • 15

1 Answers1

1

Updated

Since WooCommerce 3, the hook woocommerce_add_order_item_meta is outdated and replaced… see Woocommerce: Which hook to replace deprecated "woocommerce_add_order_item_meta".

To get separated readable custom order item data (instead of a serialized array) Try this:

add_action('woocommerce_checkout_create_order_line_item', 'add_custom_cart_item_data_as_order_item_meta', 10, 4 );
function add_custom_cart_item_data_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
    if( isset($values['custom']['length']) ){
         $item->update_meta_data( 'Length', $values['custom']['length'] );
    } 
    // elseif … ad so on
}

Code goes in function.php file of your active child theme (active theme).

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • The code in your answer didn't add anything to the order. And come to think of it I don't want to add everything in the item meta data to the order meta, only certain entries like $values['custom']['length']. I tried a different approach using the action woocommerce_add_order_item_meta and it worked. Se my comment below. – Paudun May 03 '19 at 09:00
  • if(!empty($values['custom']['length']) && isset($values['custom']['length'])){ $custom_length = $values['custom']['length']; wc_add_order_item_meta($item_id, 'Lengde i meter', $custom_length); – Paudun May 03 '19 at 09:01
  • Just replace the if-statement in my question with the if-statement in my comment. – Paudun May 03 '19 at 09:22
  • 1
    I finally got it to work. I noticed after a while that the function names didn't match in your code. I shouldn't rely on copy paste so much :p Thank you :) – Paudun May 03 '19 at 09:47