WooCommerce is without any doubt the more powerful e-commerce plugin for WordPress. And what i love with WooCommerce is that there’s an API for nearly everything. Today, i decided to show you how you can customize WooCommerce dynamically, and in particular how to add custom fields to any WooCommerce products. Here is the final result of what you’ll learn to do in this post:
As you can on the screenshot above we will see how to add custom fields to the product edition page. To do that we will be working on the functions.php file of your theme’s folder only.
To begin we will add custom fields to the product general tab, we will see later how to add custom fields to the other tabs, and how to create your own tabs.
The right hooks
The first step is to hook an action to woocommerce_product_options_general_product_data. The function linked to this hook will be responsible of the new fields display. A second hook will be taken into account to save fields values: woocommerce_process_product_meta. Basically these two actions will be done using that code:
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
Adding New Fields
The snippet above link two custom functions to the right hooks. Now we need to create those functions. Let’s start bye the first one, woo_add_custom_general_fields(), that will create the fields. Here is how the function will look like