So I've got the following code which makes me add a Barcode field to the Inventory Options of a product.
Now I also want to add this to each variations so I can easily add Variation Products when I scan the Barcode of the product via the WooCommerce Point of Sale plugin.
Here is what I got currently:
// Add Barcode field in simple product inventory options
add_action('woocommerce_product_options_sku','add_barcode',10,0);
function add_barcode(){
global $woocommerce,$post;
woocommerce_wp_text_input(
array(
'id' => '_barcode',
'label' => __('Barcode','woocommerce'),
'placeholder' => 'Scan Barcode',
'desc_tip' => 'true',
'description' => __('Scan barcode.','woocommerce'),
'value' => get_post_meta($post->ID,'_barcode',true)
)
);
}
// Save Barcode field value for simple product inventory options
add_action('woocommerce_process_product_meta','save_barcode',10,1);
function save_barcode($post_id){
if(!empty($_POST['_barcode']))
update_post_meta($post_id,'_barcode',sanitize_text_field($_POST['_barcode']));
}
// Add a Barcode field in product variations options
add_action('woocommerce_product_after_variable_attributes','add_barcode_variations',10,3);
function add_barcode_variations($loop,$variation_data,$variation){
woocommerce_wp_text_input(
array(
'id' => '_barcode[' . $variation->ID . ']',
'label' => __('Variation Barcode','woocommerce'),
'placeholder' => 'Scan Barcode',
'desc_tip' => 'true',
'description' => __('Scan barcode.','woocommerce'),
'value' => get_post_meta($variation->ID,'_barcode',true)
)
);
}
// Save Barcode field for product variations options
add_action( 'woocommerce_save_product_variation','save_barcode_variations',10,2);
function save_barcode_variations($post_id){
$barcode = $_POST['_barcode'][$post_id];
if(!empty($barcode)) update_post_meta($post_id,'_barcode',sanitize_text_field($barcode));
}
// Set POS Custom Code
add_filter('woocommerce_pos_barcode_meta_key','pos_barcode_field');
function pos_barcode_field(){
return '_barcode';
}
But the problem here is, that with that I now added a part for the variation, that if I update the product the main barcode field in the Inventory settings shows "Array" instead of the provided barcode.
I assume that this has something to do with the ID being the same for the variations as the original field other than the variationID at the end. The reason the ID requires to be the same as the WooCommerce POS plugin I'm using, is being filtered on that ID when I scan a product.
But currently can't figure out, to what I have to change to make both the Inventory Barcode Field and the Variation Barcode field to be saved properly.
As well as I'd like to add the variation field below the variation SKU field, but can't directly find the proper hook to do this.
Thanks in advance for further information.
See Question&Answers more detail:
os