php - WooCommerce: Add custom meta as hidden order item meta for internal use

I want to add some meta data to the order item in WooCommerce. These meta fields are for internal use only and shouldn't be visible.

We have some extra fields in the product like an extra fee. I want to use that fee later to work with after I export the orders.

I found a very good answer here: https://stackoverflow.com/a/41988701/1788961

add_action('woocommerce_checkout_create_order_line_item', 'add_custom_hiden_order_item_meta_data', 20, 4 );
function add_custom_hiden_order_item_meta_data( $item, $cart_item_key, $values, $order ) {

    // Set user meta custom field as order item meta
    if( $meta_value = get_user_meta( $order->get_user_id(), 'billing_enumber', true ) )
        $item->update_meta_data( 'pa_billing-e-number', $meta_value );
}

But with this example, the content from the meta fields will appear in the order details for the customer.

Is there a way to make these fields only visible in the backend and usable for internal functions?

Answer

Solution:

Updated

The simple way set any meta value as hidden order item meta data only visible on admin Order edit pages is to add an underscore at the beginning of the meta key like:

add_action('woocommerce_checkout_create_order_line_item', 'add_custom_hiden_order_item_meta_data', 20, 4 );
function add_custom_hiden_order_item_meta_data( $item, $cart_item_key, $values, $order ) {

    // Set user 'billing_enumber' custom field as admin order item meta (hidden from customer)
    if( $meta_value = get_user_meta( $order->get_user_id(), 'billing_enumber', true ) )
        $item->update_meta_data( '_billing_enumber', $meta_value );
}

Then to have a clean label name for this meta key on admin order items, you can use:

add_filter('woocommerce_order_item_display_meta_key', 'filter_wc_order_item_display_meta_key', 20, 3 );
function filter_wc_order_item_display_meta_key( $display_key, $meta, $item ) {

    // Set user meta custom field as order item meta
    if( $meta->key === '_billing_enumber' && is_admin() )
        $display_key = __("Billing E Number", "woocommerce" );

    return $display_key;    
}

This code goes in function.php file of your active child theme (or cative theme). Tested and works.

enter image description here

Source