Adding Custom Fields to Products in WooCommerce

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.

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 for 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:

Adding New Fields

The snippet above links two custom functions to the right hooks. Now we need to create those functions. Let’s start by the first one, woo_add_custom_general_fields(), that will create the fields. Here is how the function will look like

Saving Fields Values

Now that you created your WooCommerce product fields, you need to create a function to save their values once you edit the update or publish button. As we saw earlier, we will use a function called woo_add_custom_general_fields_save() hooked to woocommerce_process_product_meta. Basically, the idea behind this function is pretty simple: we check if the field is empty and if not we create a post meta using update_post_meta(). Please note that we use esc_attr() and esc_html() to secure data just a bit. Here is the code to save each field type values:

 

Retrieve Fields Values

Now that we successfully created our fields and saved their values, I guess you’d like to display those values on the frontend. In this case the best method would be to work with WooCommerce custom templates. Basically, a custom template allows you to override WooCommerce default files and use your own custom files instead. Here is a quick tutorial that will explain to you how to create your custom templates: http://docs.woothemes.com/document/template-structure/

To get those values we just need to use the popular get_post_meta() function. That’s pretty much all you need.

Example:

About the Author

dr.code.skm

I am backend developer with passion in Web Application development using latest technologies like Laravel, PHP7, React, ECMAScript 6 and WordPress. I prefer spending time analyzing big data with Apache Spark. Apart from that, I do photography.