Tested on php 7.4 wp 5.5.1 wooCommerce 4.5.2
The following code add a select box on each product variation
<?php
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
function variation_settings_fields( $loop, $variation_data, $variation ) {
// Select
woocommerce_wp_select(
array(
'id' => '_selectB2cB2b[' . $variation->ID . ']',
'label' => __( 'Visible on', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_selectB2cB2b', true ),
'options' => array(
'both' => __( 'Shop and business site', 'woocommerce' ),
'onlyshop' => __( 'Only on Shop', 'woocommerce' ),
'onlybusiness' => __( 'Only on Business', 'woocommerce' )
),
'description' => __( 'Questa opzione limita la visualizzazione della variante a determinate tipologie di utente (business o shop)', 'woocommerce' ),
'desc_tip' => true
)
);
}
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $variation_id, $loop ) {
$selectB2cB2b = $_POST['_selectB2cB2b'][ $variation_id ];
If( isset($selectB2cB2b)){
update_post_meta( $variation_id, '_selectB2cB2b', esc_attr( $selectB2cB2b ));
}
}
It can be called on the product page by:
var_dump(get_post_meta( $available_variations[$key][‘variation_id’], ‘licence_ppl’, true ));
Note that in this case i’m in a foreach [foreach ($available_variations as $key => $value) ]
You can add the following type of custom fields
- Text Field
- Number Field
- Textarea
- Dropdown Select
- Checkbox
- Hidden field
For more informations, you can check this interesting article from Rémi Corson
Questions? Suggestions? Please leave a comment below.
1 thought on “Add custom fields to variation in wooCommerce admin panel”