This is how, I add an admin custom field for product Variations:
add_action( 'woocommerce_variation_options_pricing', 'add_custom_field_to_variations', 10, 3 );
function add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Custom Field', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
) );
}
Save custom field on product variation save:
add_action( 'woocommerce_save_product_variation', 'save_custom_field_variations', 10, 2 );
function save_custom_field_variations( $variation_id, $i ) {
$custom_field = $_POST['custom_field'][$i];
if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
}
Store custom field value into variation data
add_filter( 'woocommerce_available_variation', 'add_custom_field_variation_data' );
function add_custom_field_variation_data( $variations ) {
$variations ['custom_field'] = '<div class="woocommerce_custom_field">Custom Field: <span>' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
return $variations;
}
The value is saving and displaying in the single product page but the below function is not returning the value
Trying to retrieve Value of the custom field in a function:
add_filter('woocommerce_variation_prices_price', 'get_custom_variable_price' )
function get_custom_variable_price() {
global $post;
$custom_value = get_post_meta( $variations[ 'variation_id' ], 'custom_field', true );
$custom_value = (float)$custom_value;
return $custom_value;
}
I need to get just the value (which is float number):