In this tutorial you will learn how you can easily add the custom fields in product page and display it on front end. To add custom fields in product page we don't need any plugin to install, just using some hooks and code we will do it.
Custom field will be display like this above screenshot. You need to add the following code in your theme functions.php.
Display Field:
// Display Fields
add_action('woocommerce_product_options_general_product_data', 'aj_woocommerce_product_custom_fields');
function aj_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 Field',
'label' => __('Custom Product Field', 'woocommerce'),
'desc_tip' => 'true'
)
);
echo '</div>';
}
In the above code we used "woocommerce_product_options_general_product_data" hook for display text custom field on product page. Same as above you can add number and textarea field.
//Custom Product Number Field
woocommerce_wp_text_input(
array(
'id' => '_custom_product_number_field',
'placeholder' => 'Custom Product Number Field',
'label' => __('Custom Product Number Field', 'woocommerce'),
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
//Custom Product Textarea
woocommerce_wp_textarea_input(
array(
'id' => '_custom_product_textarea',
'placeholder' => 'Custom Product Textarea',
'label' => __('Custom Product Textarea', 'woocommerce')
)
);
Save Fields: Using the following code you can save that custom created fields values into database.
// Save Fields
add_action('woocommerce_process_product_meta', 'ad_woocommerce_product_custom_fields_save');
function ad_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));
}
In the above code we used "woocommerce_process_product_meta" hook and update_post_meta function to save the values.
Get Custom Field Values from Database
// Display the value of custom product text field
echo get_post_meta($productID, '_custom_product_text_field', true);
Using this above code you can display product custom field anywhere you want, you just need product ID.
That's it, you can add any number of fields you want to add in product page and display it on product details page or anywhere you want to display.
0 Comments