I'm trying to add a custom field to product variations, and display the custom field value on products in the "additional information area".
I'm working from "WooCommerce: Add Custom Field to Each Product Variation".
The custom field is working fine, but I cannot seam to display the value on the product page.
This is what I have so far:
// 1. Add custom field input @ Product Data > Variations > Single Variation
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 )
));
}
// 2. 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 ) );
}
}
// 3. 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;
}
// 4. Display custom field on the additional information area
function Display_product_attributes2($product_attributes, $variations){
$product_attributes['custom_field'] = [
'label' => __('custom', 'text-domain'),
'value' => get_post_meta( $variation_id, '_custom_field', true ),
];
return $product_attributes;
}
add_filter('woocommerce_display_product_attributes', 'Display_product_attributes2', 10, 2);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…