The code for adding custom fields in the background is as follows:
// 1. Add custom field input @ Product Data > Variations > Single Variation
function bbloomer_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 )
)
);
}
add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 );
// 2. Save custom field on product variation save
function bbloomer_save_custom_field_variations( $variation_id, $i ) {
$custom_field = $_POST['custom_field'][$i];
if ( ! empty( $custom_field ) ) {
update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
} else delete_post_meta( $variation_id, 'custom_field' );
}
add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );
// 3. Store custom field value into variation data
function bbloomer_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;
}
add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
So, How to display this newly added custom field and the existing SKU field under the product title on the front product page at the same time, and: when selecting different variants, the corresponding custom field and SKU field will also be displayed dynamically.
I tried but it doesn’t show up below the title
2
Answers
The code from BBloomer is a bit outdated…
To display the selected variation custom field below the product title, use the following instead:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
You have to use get_post_meta() function to show it in the frontend
Note: Remember to pass the parameters ($product->ID and slug) correctly