A few months ago I wrote a post on how to add custom fields to WooCommerce products within the administration, and many of you ask me how to add custom fields to products variations. So I decided to write this tutorial to help you create new fields for each WooCommerce product variation. The final result of this tutorial will look like this:
Each function will be hooked to these specific actions:
I will cover only 6 fields types for the moment, and I will probably create a new post for advanced fields later. In this tutorial, you will learn how to add these custom fields to variations:
- Text Field
- Number Field
- Dropdown Select
- Hidden field
A quick explanation
Basically the method is more or less the same what i explained in my previous post regarding custom fields for products, b
Registering fields is pretty basic as you see we use the WooCommerce builtin functions (All these functions are located in WooCommerce/Admin/WritePanels/writepanels-init.php.):
Finally, the only “tricky” part is the within the save_variation_settings_fields() function, where you need to make sure that each field uses the update_post_meta() function, otherwise your field won’t be saved. The use of a “for” loop is needed to loop through all variations.
To get those values on the frontend we just need to use the popular get_post_meta() function. That’s pretty much all you need.
Displaying Fields Values on the Frontend with WooCommerce 2.5+
WooCommerce introduced wp.template, and it’s now easier to display variations custom fields values based on the selection of the attribute value in the dropdown select. You need to add the following function to functions.php:
And now you need to edit the custom template that display the variation fields. This file is called variation.php and is located in wp-plugins/plugins/woocommerce/templates/single-product/add-to-cart/. Do not edit this file directly but instead, duplicate it and place it in a folder called woocommerce/templates/single-product/add-to-cart/ in your theme folder (Keep in mind: never edit core files). Add this code: