How to Add Single Product Page Custom Field in WooCommerce

Here, we will discuss How to Add Single Product Page Custom Field in WooCommerce? When you want to display any information in a special field or area where you can add a custom field on wooconnerce single product page.

First go to FTP and download the file called functions.php. Open in any code editor. Paste below code here.

Add WooCommerce Custom Fields on Product Page

//Add WooCommerce Custom Fields on Product Page
function woocommerce_product_custom_fields()
{
$args = array(
  'id' => 'woocommerce_custom_fields',
  'label' => __('Add WooCommerce Custom Fields', 'cwoa'),
);
woocommerce_wp_text_input($args);
}
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');

Save Custom Fields WooCommerce

//Save Custom Fields WooCommerce
function save_woocommerce_product_custom_fields($post_id)
{
  $product = wc_get_product($post_id);
  $custom_fields_woocommerce_title = isset($_POST['woocommerce_custom_fields']) ? $_POST['woocommerce_custom_fields'] : '';
  $product->update_meta_data('woocommerce_custom_fields', sanitize_text_field($custom_fields_woocommerce_title));
  $product->save();
}
add_action('woocommerce_process_product_meta', 'save_woocommerce_product_custom_fields');

WooCommerce Display Custom Fields On Product Page

//WooCommerce Display Custom Fields On Product Page
function woocommerce_custom_fields_display()
{
  global $post;
  $product = wc_get_product($post->ID);
  $custom_fields_woocommerce_title = $product->get_meta('woocommerce_custom_fields');
  if ($custom_fields_woocommerce_title) {
    printf(
      '%s',
      esc_html($custom_fields_woocommerce_title)
    );
  }
}
add_action('woocommerce_before_add_to_cart_button', 'woocommerce_custom_fields_display');
What's your reaction?
0COOL0WTF0LOVE0LOL