I would like to add a text field in the back-end Woocommerce product page and displaying/echo the text on the front-end below the Product title.
Now I have the ‘custom field box’ to write a text in the back-end (see screenshot), but I don’t know how I can showing the text on the front-end. Can someone help me with this code?
I followed this page, but it is only for archive pages…
Add a custom field value below product title in WooCommerce archives pages
Thank you in advance!
jerry
Functions.php
// Display Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');
// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields()
{
global $woocommerce, $post;
echo '<div class="product_custom_field">';
// Custom Product Text Field
woocommerce_wp_text_input(
array(
'id' => '_custom_product_text_field',
'placeholder' => 'Custom Product Text Field',
'label' => __('Custom Product Text Field', 'woocommerce'),
'desc_tip' => 'true'
)
);
}
function woocommerce_product_custom_fields_save($post_id)
{
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, '_custom_product_text_field', esc_attr($woocommerce_custom_product_text_field));
}
2
Answers
Your solution is the right hook, when you use add_action() you need to choose the right hook to insert your code in the right location.
Probebly the location you want is "woocommerce_before_add_to_cart_form";
I’m not sure about the exact location but you can just change "woocommerce_before_add_to_cart_form" and place the right hook you want.
This is a great article that shows the location and the required hook for every location. Let me know what you get!
Add the following to display that product custom field in single product pages below product title:
Code goes in functions.php file of your active child theme (or active theme). It should work.
Then it will call the function, that you are already using, to display the custom field on product archive pages:
Related: WooCommerce action hooks and overriding templates