Even if WooCommerce provides a lot of ways to add custom data to your products, sometimes is just not enough, or no the best way to do it. You may need to add some custom fields that will properly show on your product page.
In this tutorial, you will learn how to create custom fields for your products. I won’t cover how to add custom fields on variations for now, it will be a separate tutorial.
Your custom fields will be added to the General tab in the product data section. You can add various types of fields, from simple text fields to dropdowns and text areas.
To begin, you need to hook the function that will print the fields to
woocommerce_product_options_general_product_data, like this:
Then you have to add the code to print the fields. There are various functions in WooCommerce to print different fields.
Let’s start with something simple, adding a text field:
This code will print a text input in your general data section while editing a product. As I already said above, you can have different fields, here is a list of functions you can use for each type of field:
There are also other types of fields you can add but that do not have a specific function. They are the fields
To create them just use the function
woocommerce_wp_text_input and in the array that you pass as a parameter, where I specified the field ID, description, etc., above, add also the index
'type' => 'tel' or
Saving the values
Printing the fields is not enough. If you don’t add a function to save their value, as soon as you update the product the changes will be lost.
The hook to use in this case is
woocommerce_process_product_meta. You will find the values of your custom fields in the global variable
$_POST. To save the field in the example above use this code:
Add as many fields as you need after line 5 of this snippet.
Make sure to escape them for safety and, if needed, perform other actions on them.