0

I'm trying to add a metadata to each order item inside wp_woocommerce_order_itemmeta table. For example, in one order, there're two T-shirts and each T-shirt can be printed with a unique customized name, OR ALL shirts in one order could have the same customized name. I've seen examples using update_post_meta but that is adding metadata to the entire order (to the wp_postmeta table).

Then, I saw this Woocommerce: Which hook to replace deprecated "woocommerce_add_order_item_meta" and followed the example as below.

    // Save custom data to order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );

function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    // Get a product custom field value
    $custom_field_value = get_post_meta( $item->get_product_id(), 'design', true );


    // Update order item meta
    if ( ! empty( $custom_field_value ) ){
        $item->update_meta_data( 'design', $custom_field_value );
    }
}

But it doesn't work. I have a custom field called 'design' but my wp_woocommerce_order_itemmeta table does not contain the 'design' metadata.

Did I do something wrong?

This is how I create the custom field and how I save its data. I managed to only save the metadata in wp_postmeta table.

add_action('woocommerce_after_order_notes', 'cw_custom_checkbox_fields');

add_action('woocommerce_checkout_update_order_meta', 'cw_checkout_order_meta');

function cw_custom_checkbox_fields( $checkout ) {

     woocommerce_form_field( 'design', array(
      'type'          => 'text',
    ), $checkout->get_value( 'design' ) );
}

function cw_checkout_order_meta( $order_id ) {
    if ($_POST['design']) update_post_meta( $order_id, 'design', esc_attr($_POST['design']));
}
warnerque
  • 83
  • 10

1 Answers1

0

Try this instead,

add_action( 'woocommerce_checkout_create_order_line_item', 'add_my_meta_to_line_item', 10, 4 );

function add_my_meta_to_line_item( $item, $cart_item_key, $values, $order) {
  if ($_POST['design']) $item->add_meta_data( 'design', esc_attr($_POST['design'], true ));
}
vyap56
  • 180
  • 8