Replies: 0
I have a woocommerce store and I am building a plugin that will share some of the same data for product variations.
My plugin will list some of the product variation fields for all product variations and I need to know the best way to manage these fields (some of them custom variation fields) ie. CRUD via my plugin eg. For example: **SKU, price, stock, Conditionnement and Sachet** (The last two fields are the custom fields)
So I have the woocommerce side of things set up and I have the plugin set up but how do I add the fields I need from woocommerce to my plugin and how do I update the meta data?
I think I may need to use the add_meta_box
function to add the fields on screen but I worry about duplicating data instead of updating existing data in woocommerce.
I am not sure where to start with this. Can anyone advise?
Below is the code in my functions.php file for adding the custom fields.
/* add custom fields to product variations*/
add_action( ‘woocommerce_product_after_variable_attributes’, ‘variation_settings_fields’, 10, 3 );
add_action( ‘woocommerce_save_product_variation’, ‘save_variation_settings_fields’, 10, 2 );
add_filter( ‘woocommerce_available_variation’, ‘load_variation_settings_fields’ );
function variation_settings_fields( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
‘id’ => “conditionnement{$loop}”,
‘name’ => “conditionnement[{$loop}]”,
‘value’ => get_post_meta( $variation->ID, ‘conditionnement’, true ),
‘label’ => __( ‘Conditionnement’, ‘woocommerce’ ),
‘desc_tip’ => false,
‘wrapper_class’ => ‘form-row form-row-full’,
)
);
woocommerce_wp_text_input(
array(
‘id’ => “sachet{$loop}”,
‘name’ => “sachet[{$loop}]”,
‘value’ => get_post_meta( $variation->ID, ‘sachet’, true ),
‘label’ => __( ‘Sachet’, ‘woocommerce’ ),
‘desc_tip’ => false,
‘wrapper_class’ => ‘form-row form-row-full’,
)
);
}
function save_variation_settings_fields( $variation_id, $loop ) {
$custom_field1 = $_POST[‘conditionnement’][ $loop ];
if ( ! empty( $custom_field1 ) ) {
update_post_meta( $variation_id, ‘conditionnement’, esc_attr( $custom_field1 ));
}
$custom_field2 = $_POST[‘sachet’][ $loop ];
if ( ! empty( $custom_field2 ) ) {
update_post_meta( $variation_id, ‘sachet’, esc_attr( $custom_field2 ));
}
}
function load_variation_settings_fields( $variation ) {
$variation[‘conditionnement’] = get_post_meta( $variation[ ‘variation_id’ ], ‘conditionnement’, true );
$variation[‘sachet’] = get_post_meta( $variation[ ‘variation_id’ ], ‘sachet’, true );
return $variation;
}`