Add custom meta field to woocommerce product

Add custom field to woocommerce admin product general tab. To add custom meta field in product admin just add below code in your themes function.php file or any custom plugin.

//Add custom field to product meta
function woocommerce_product_custom_fields_dna(){
  	$args = array(
    	'id' => 'woocommerce_color_fields',
    	'label' => __('Color', 'color'),
  	);
  	woocommerce_wp_text_input($args);
}
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields_dna');
//Save custom meta field
function save_woocommerce_product_custom_fields_dna($post_id){
	    $product = wc_get_product($post_id);
	    $color_title = isset($_POST['woocommerce_color_fields']) ? $_POST['woocommerce_color_fields'] : '';
	    $product->update_meta_data('woocommerce_color_fields', sanitize_text_field($color_title));
	    $product->save();
}
add_action('woocommerce_process_product_meta', 'save_woocommerce_product_custom_fields_dna');
//Display in storefront before add to cart button
function woocommerce_custom_fields_display_dna(){
  global $post;
  $product = wc_get_product($post->ID);
    $color_title = $product->get_meta('woocommerce_color_fields');
  if ($color_title) {
      printf(
            '<div><label>%s</label><input type="text" id="woocommerce_color_fields" name="woocommerce_color_fields" value=""></div>',
            esc_html($color_title)
      );
  }
}
add_action('woocommerce_before_add_to_cart_button', 'woocommerce_custom_fields_display_dna');

Leave a Reply