Add a custom text field to WooCommerce admin product data “Variations”

Overriding core files is really something to avoid absolutely for many reasons.

To add a custom field to product variations options prices and save the value on save, use this:

// Admin: Add custom field in product variations options pricing
add_action( 'woocommerce_variation_options_pricing', 'add_variation_custom_option_pricing', 10, 3 );
function add_variation_custom_option_pricing( $loop, $variation_data, $variation ){

   woocommerce_wp_text_input( array(
        'id'            => '_cost_price['.$loop.']',
        'label'         => __("Cost Price", "woocommerce") . ' (' . get_woocommerce_currency_symbol() . ')',
        'class' => 'short wc_input_price',
        'data_type'     => 'price',
        'wrapper_class' => 'form-row form-row-first',
        'value'         => wc_format_localized_price( get_post_meta( $variation->ID, '_cost_price', true ) )
    ) );
}

// Admin: Save custom field value from product variations options pricing
add_action( 'woocommerce_save_product_variation', 'save_variation_custom_option_pricing', 10, 2 );
function save_variation_custom_option_pricing( $variation_id, $i ){
    if( isset($_POST['_cost_price'][$i]) ){
        update_post_meta( $variation_id, '_cost_price', wc_clean( wp_unslash( str_replace( ',', '.', $_POST['_cost_price'][$i]) ) ) );
    }
}

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

enter image description here


USAGE – If you need to use it to get the value:

1) From the variation ID

$cost_price = update_post_meta( $variation_id, '_cost_price', true );

2) From the product variation object

$cost_price = $variation->get_meta('_cost_price');