Display product custom fields on WooCommerce Admin Order Items also for variable products

Viewed 1117

Based on Show custom fields on the order editing page in WooCommerce answer code where I did some slight changes:

add_action( 'woocommerce_before_order_itemmeta', 'add_admin_order_item_custom_fields', 10, 2 );
function add_admin_order_item_custom_fields( $item_id, $item ) {
    // Targeting line items type only
    if( $item->get_type() !== 'line_item' ) return;

    $product = $item-> get_product();
    $value1  = $product->get_meta('model_number');

    if ( ! empty($value1) ) {
        echo '<table cellspacing="0" class="display_meta">';

        if ( ! empty($value1) ) {
            echo '<tr><th>' . __("Modelnummer", "woocommerce") . ':</th><td>' . $value1 . '</td></tr>';
        }
        echo '</table>';
    }
}

I would like to make that code works for variable products custom fields too.

What do I need to change to make it work for variable products?

1 Answers

The following will get the parent variable product custom field if it is a product variation with no custom field set for it:

add_action( 'woocommerce_before_order_itemmeta', 'add_admin_order_item_custom_fields', 10, 2 );
function add_admin_order_item_custom_fields( $item_id, $item ) {
    // Targeting line items type only
    if( $item->get_type() !== 'line_item' ) return;

    $product       = $item->get_product();
    $model_number  = $product->get_meta('model_number');
    
    // Get the parent variable product custom field if empty value
    if( $item->get_variation_id() > 0 && empty($model_number) ) {
        $parent_product = wc_get_product( $item->get_product_id() );
        $model_number   = $parent_product->get_meta('model_number');
    }

    if ( ! empty($model_number) ) {
        echo '<table cellspacing="0" class="display_meta"><tr>
            <th>' . __("Model number", "woocommerce") . ': </th>
            <td>' . $model_number . '</td>
        </tr></table>';
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related