How to add custom fields to a WooCommerce product

Programmatically create and display custom text fields in WooCommerce

In this post, I’m going to walk through the entire process of adding custom fields to a WooCommerce product. Custom fields (also called product addons) include text fields, select fields, checkboxes, and so on. They allow the user to enter additional, personalised information about a product. The post will cover creating and displaying the custom fields, adding the custom field data to the cart, and inserting the data in emails and orders.

I will include code examples throughout the article. By the end you will have learned to build your own custom field plugin for WooCommerce. The plugin will:

  • Create a custom field in Product Data section of a WooCommerce product
  • Use the value saved in that field to display a text input field in the product single page
  • Save the user input in the custom field to cart meta data
  • Pass the value of the custom field to the order object

Custom fields without coding

We’ll go through the process from start to finish. However, if you are looking for a simpler way to add custom fields, then take a look at the Product Extras for WooCommerce plugin. It will allow you to add many types of field to your products, including text inputs, number inputs, checkboxes, radio buttons, select fields, even file uploads. You can add costs, subtract costs, and use conditional logic.

Extra fields, options and addons for WooCommerce products

What’s in this article?

If you prefer to build the code yourself, then read on. The article is organised into the following sections:

I’ve also included all the code used in the article in its entirety at the end.

Why add custom fields

For detailed information about personalised products, you can take a look at How to personalize WooCommerce products with additional options. That article includes:

  • The differences between custom fields and variations
  • Facts and figures on the benefits of including custom fields in your products
  • Ideas for the types of products that use custom fields

However, in summary, it’s worth noting that custom fields will improve customer retention and is likely to boost sales. Typical examples of products with custom fields include:

  • Menu ordering – e.g. build your own pizza, build your own sandwich
  • Personalised greeting cards
  • Gift wrapping
  • Extended warranties
  • And anything else your business requires

Adding a custom field in the back-end

Let’s start by looking at some code to add a custom field to the back-end of WooCommerce. This will add a new field in the Product Data section of a WooCommerce product.

/**
* Display the custom text field
* @since 1.0.0
*/
function cfwc_create_custom_field() {
$args = array(
'id' => 'custom_text_field_title',
'label' => __( 'Custom Text Field Title', 'cfwc' ),
'class' => 'cfwc-custom-field',
'desc_tip' => true,
'description' => __( 'Enter the title of your custom text field.', 'ctwc' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'cfwc_create_custom_field' );

This short function uses a standard WooCommerce function, called woocommerce_wp_text_input, to display a text field in the Product Data section.

WooCommerce custom field

You’ll notice that woocommerce_wp_text_input accepts several parameters:

  • id
  • label
  • class
  • desc_tip
  • description

You can find a complete list of the parameters in the wc-meta-box-functions.php file. There are several cognate functions, all with nice self-explanatory names, like:

  • woocommerce_wp_hidden_input
  • woocommerce_wp_textarea_input
  • woocommerce_wp_checkbox

These functions greatly simplify the task of adding custom fields to WooCommerce products.

Hooking the custom field function

To ensure that the custom field displays in the correct place – in this case, it’s just on the General tab – we need to hook our function to the correct action: woocommerce_product_options_general_product_data.

If you wanted to add your custom field to a different tab, you could try actions like:

  • woocommerce_product_options_inventory_product_data
  • woocommerce_product_options_shipping

Again, the names are clear and self-explanatory.

Saving the custom field value

With this code, we’ve got a really simple way to add custom fields to products, using standard WooCommerce functions and actions. All we need to do know is save the value of the field when the product is updated.

/**
* Save the custom field
* @since 1.0.0
*/
function cfwc_save_custom_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['custom_text_field_title'] ) ? $_POST['custom_text_field_title'] : '';
$product->update_meta_data( 'custom_text_field_title', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'cfwc_save_custom_field' );

This function runs when the product is first published or when it’s updated. It looks for a value in our custom field, sanitises it, then saves it as product meta data using the CRUD methodology introduced to WooCommerce a few versions ago.

The function hooks to the woocommerce_process_product_meta action.

Displaying the custom field on the front-end

Now that we’ve created the custom field on the back-end, we can start to think about displaying it on the single product page.

We will check if the custom field has a value. If it does, we’ll use that value as the title of the input field on the front end. The user will be able to enter some text, which will get saved as part of the cart meta data when they add the product to the cart.

WooCommerce custom field frontend

Here’s the code to display the custom field on the product page:

/**
* Display custom field on the front end
* @since 1.0.0
*/
function cfwc_display_custom_field() {
global $post;
// Check for the custom field value
$product = wc_get_product( $post->ID );
$title = $product->get_meta( 'custom_text_field_title' );
if( $title ) {
// Only display our field if we've got a value for the field title
printf(
'<div class="cfwc-custom-field-wrapper"><label for="cfwc-title-field">%s</label><input type="text" id="cfwc-title-field" name="cfwc-title-field" value=""></div>',
esc_html( $title )
);
}
}
add_action( 'woocommerce_before_add_to_cart_button', 'cfwc_display_custom_field' );

This function creates a $product object based on the product ID so that it can look in the product meta data for a value for the custom_text_field_title field. If it finds a value, then it will display a text input field and label.

Note that the function is hooked to the woocommerce_before_add_to_cart_button action. Hooking it to this action ensures that the input field is included in the cart form, which means that its value will be available when the product is added to the cart. Which is what we’ll look at next.

Validating custom field values

When a user enters some text into our custom field, we might want to check that the text conforms to some criteria we’ve laid down before we allow the item to be added to the cart. We do that using the woocommerce_add_to_cart_validation filter.

The code below performs a simple check when the user clicks ‘Add to Cart’ to ensure that they have entered some text in the custom field. Essentially, this makes the field required in order for the user to add it to their cart.

/**
* Validate the text field
* @since 1.0.0
* @param Array $passed Validation status.
* @param Integer $product_id Product ID.
* @param Boolean $quantity Quantity
*/
function cfwc_validate_custom_field( $passed, $product_id, $quantity ) {
if( empty( $_POST['cfwc-title-field'] ) ) {
// Fails validation
$passed = false;
wc_add_notice( __( 'Please enter a value into the text field', 'cfwc' ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'cfwc_validate_custom_field', 10, 3 );

The woocommerce_add_to_cart_validation provides you with three parameters:

  • $passed – a boolean value to indicate whether validation is successful or not
  • $product_id – the product ID
  • $quantity – the value of the quantity field

In this function, we simply get the value of the cfwc-title-field, which we added to the cart form in the previous step. If it’s empty, we display a message to the user and set the $passed parameter to false. Because this is a filter, we need to return a value.

How to add a message if the product fails validation

The function uses wc_add_notice to add a message to the WooCommerce notice. This function accepts two arguments:

  • Message – the text to display
  • Status – can be ‘error’, ‘success’, or ‘notice’. Most themes would style these notices differently

WooCommerce validation notice

Adding custom values to the cart

Assuming the product successfully validates, it’ll get added to the WooCommerce cart object. We can add our own meta data to this object so that we can use it later in the process, e.g. on the cart and checkout pages and for orders and emails.

/**
* Add the text field as item data to the cart object
* @since 1.0.0
* @param Array $cart_item_data Cart item meta data.
* @param Integer $product_id Product ID.
* @param Integer $variation_id Variation ID.
* @param Boolean $quantity Quantity
*/
function cfwc_add_custom_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if( ! empty( $_POST['cfwc-title-field'] ) ) {
// Add the item data
$cart_item_data['title_field'] = $_POST['cfwc-title-field'];
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'cfwc_add_custom_field_item_data', 10, 4 );

This function hooks to woocommerce_add_cart_item_data, which filters the data passed to the cart object when a product is added to the cart. So here we check that the cfwc-title-field has a value then add that to $cart_item_data.

Updating the product price programmatically

Let’s imagine, for the sake of argument, that we would like to increase the cost of the product if the custom field has a value. There’s a longer article on updating the price programmatically in WooCommerce here but I’ll cover the essentials below as well.

The first thing to do is expand the cfwc_add_custom_field_item_data function above.

/**
* Add the text field as item data to the cart object
* @since 1.0.0
* @param Array $cart_item_data Cart item meta data.
* @param Integer $product_id Product ID.
* @param Integer $variation_id Variation ID.
* @param Boolean $quantity Quantity
*/
function cfwc_add_custom_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if( ! empty( $_POST['cfwc-title-field'] ) ) {
// Add the item data
$cart_item_data['title_field'] = $_POST['cfwc-title-field'];
$product = wc_get_product( $product_id ); // Expanded function
$price = $product->get_price(); // Expanded function
$cart_item_data['total_price'] = $price + 100; // Expanded function
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'cfwc_add_custom_field_item_data', 10, 4 );

You can see that we’ve generated a WooCommerce product by using the $product_id which is passed in as one of our parameters. From the product, we can get the price, then I’ve just added an arbitrary figure to this price.

Now we need to use the updated price when the cart items are totalled up.

Calculating the custom price

To update the product price to the updated price in the cart, we use the woocommerce_before_calculate_totals action:

/**
* Update the price in the cart
* @since 1.0.0
*/
function cfwc_before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Iterate through each cart item
foreach( $cart_obj->get_cart() as $key=>$value ) {
if( isset( $value['total_price'] ) ) {
$price = $value['total_price'];
$value['data']->set_price( ( $price ) );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'cfwc_before_calculate_totals', 10, 1 );

You can see here that the function iterates through the contents of the cart one item at a time. It checks for the total_price parameter that would have been set when the product was added to the cart. If the parameter is present, the price of the cart item is updated.

Displaying custom fields in the cart and checkout

Let’s look at how to display the custom field value in the cart and the checkout. We can use the same filter for both pages, so we only need to write one function:

/**
* Display the custom field value in the cart
* @since 1.0.0
*/
function cfwc_cart_item_name( $name, $cart_item, $cart_item_key ) {
if( isset( $cart_item['title_field'] ) ) {
$name .= sprintf(
'<p>%s</p>',
esc_html( $cart_item['title_field'] )
);
}
return $name;
}
add_filter( 'woocommerce_cart_item_name', 'cfwc_cart_item_name', 10, 3 );

The function checks each item in the cart for our title_field parameter. If it’s set, then it adds the title field to the product name as displayed in the cart.

Note that the woocommerce_cart_item_name filter works on the cart and checkout forms.

Displaying custom fields in the WooCommerce order and email confirmations

Having ensured that our custom field is visible to the user in the cart and checkout forms, we now need to pass its value to the order when the user checks out.

/**
* Add custom field to order object
*/
function cfwc_add_custom_data_to_order( $item, $cart_item_key, $values, $order ) {
foreach( $item as $cart_item_key=>$values ) {
if( isset( $values['title_field'] ) ) {
$item->add_meta_data( __( 'Custom Field', 'cfwc' ), $values['title_field'], true );
}
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'cfwc_add_custom_data_to_order', 10, 4 );

We can do this very easily using the woocommerce_checkout_create_order_line_item action. Like the filter for the product name in the cart, we just check the cart item for the title_field parameter. If it’s present, we add its value as meta data to the $item object.

This will ensure that our custom field value is displayed on the order confirmation field that the user sees once they have checked out, the order in the backend, and on the confirmation email to the admin and to the customer.

WooCommerce order page

Complete plugin

Here is the code for the entire plugin:

<?php
/**
* Plugin Name: Custom Fields for WooCommerce
* Description: Add custom fields to WooCommerce products
* Version: 1.0.0
* Author: Gareth Harris
* Author URI: https://catapultthemes.com/
* Text Domain: cfwc
* WC requires at least: 3.4.0
* WC tested up to: 3.4.2
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Display the custom text field
* @since 1.0.0
*/
function cfwc_create_custom_field() {
$args = array(
'id' => 'custom_text_field_title',
'label' => __( 'Custom Text Field Title', 'cfwc' ),
'class' => 'cfwc-custom-field',
'desc_tip' => true,
'description' => __( 'Enter the title of your custom text field.', 'ctwc' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'cfwc_create_custom_field' );
/**
* Save the custom field
* @since 1.0.0
*/
function cfwc_save_custom_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['custom_text_field_title'] ) ? $_POST['custom_text_field_title'] : '';
$product->update_meta_data( 'custom_text_field_title', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'cfwc_save_custom_field' );
/**
* Display custom field on the front end
* @since 1.0.0
*/
function cfwc_display_custom_field() {
global $post;
// Check for the custom field value
$product = wc_get_product( $post->ID );
$title = $product->get_meta( 'custom_text_field_title' );
if( $title ) {
// Only display our field if we've got a value for the field title
printf(
'<div class="cfwc-custom-field-wrapper"><label for="cfwc-title-field">%s</label><input type="text" id="cfwc-title-field" name="cfwc-title-field" value=""></div>',
esc_html( $title )
);
}
}
add_action( 'woocommerce_before_add_to_cart_button', 'cfwc_display_custom_field' );
/**
* Validate the text field
* @since 1.0.0
* @param Array $passed Validation status.
* @param Integer $product_id Product ID.
* @param Boolean $quantity Quantity
*/
function cfwc_validate_custom_field( $passed, $product_id, $quantity ) {
if( empty( $_POST['cfwc-title-field'] ) ) {
// Fails validation
$passed = false;
wc_add_notice( __( 'Please enter a value into the text field', 'cfwc' ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'cfwc_validate_custom_field', 10, 3 );
/**
* Add the text field as item data to the cart object
* @since 1.0.0
* @param Array $cart_item_data Cart item meta data.
* @param Integer $product_id Product ID.
* @param Integer $variation_id Variation ID.
* @param Boolean $quantity Quantity
*/
function cfwc_add_custom_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if( ! empty( $_POST['cfwc-title-field'] ) ) {
// Add the item data
$cart_item_data['title_field'] = $_POST['cfwc-title-field'];
$product = wc_get_product( $product_id ); // Expanded function
$price = $product->get_price(); // Expanded function
$cart_item_data['total_price'] = $price + 100; // Expanded function
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'cfwc_add_custom_field_item_data', 10, 4 );
/**
* Update the price in the cart
* @since 1.0.0
*/
function cfwc_before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Iterate through each cart item
foreach( $cart_obj->get_cart() as $key=>$value ) {
if( isset( $value['total_price'] ) ) {
$price = $value['total_price'];
$value['data']->set_price( ( $price ) );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'cfwc_before_calculate_totals', 10, 1 );
/**
* Display the custom field value in the cart
* @since 1.0.0
*/
function cfwc_cart_item_name( $name, $cart_item, $cart_item_key ) {
if( isset( $cart_item['title_field'] ) ) {
$name .= sprintf(
'<p>%s</p>',
esc_html( $cart_item['title_field'] )
);
}
return $name;
}
add_filter( 'woocommerce_cart_item_name', 'cfwc_cart_item_name', 10, 3 );
/**
* Add custom field to order object
*/
function cfwc_add_custom_data_to_order( $item, $cart_item_key, $values, $order ) {
foreach( $item as $cart_item_key=>$values ) {
if( isset( $values['title_field'] ) ) {
$item->add_meta_data( __( 'Custom Field', 'cfwc' ), $values['title_field'], true );
}
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'cfwc_add_custom_data_to_order', 10, 4 );

Final thoughts

Hopefully, you’ve been able to follow through step by step how to create, add and save custom field data in WooCommerce. Don’t forget to check out the Product Extras plugin for extensive extra functionality.

Extra fields, options and addons for WooCommerce products


Popular Posts

28 thoughts on “How to add custom fields to a WooCommerce product

Hi Gareth,

Thanks for your great plugin. I have use it with my website. We see one small bug in the plugin. When i use it together with variable products the section will display twice.

See screenshot:
https://www.euronormportal.com/img/cfwc-bug.jpg

Reply

Hi Dustin – I think that is related to your theme. Can you try testing with a standard theme, like Twenty Seventeen, to see if you get the same problem?

Reply

Hi,

Thank you for these golden information I really needs it.

But, I have one question can I show the custom fields in the product page depends on the category.
For example I sell many items in my website ( Books, Electronics, Clothes) So for book I only want to show ISBN, Publisher, Author but in clothes for example size and color but if I use that code now and add all these custom fields it will show in all the product category is there any way to show the custom fields depends on my category?

Thanks in advance,

Reply

Thanks for the excellent article, where can i find more information on the “woocommerce_product_options_general_product_data” functions, i could not find anything in the woocommerce documentation.

Reply

Great article,

Is it possible to update a custom meta value that was added to the product as it was added to the cart.

I’m able to establish the cart item key of the item I want to update but then unsure how to update the meta value?

Any suggestions would be really appreciated.

Reply

You can use something like WC()->get_cart() to get the cart contents.

Reply

Great information, thank you!

I used this and added 3 custom fields – https://prnt.sc/kx1qh7
Now, problem is how to save all 3 without writing separate methods?

Any help would be really appreciated.

Reply

Hi, great job!!!
I’m testing this script (in functions.php file) and works OK, but for the products that don’t have a custom field assigned in the back-end (so no custom text field is displayed on the front-end product page), the validation keeps failing and the clients is getting the warning “Please enter a value into the text field” every time they want to add a product to the cart. In the products WITH custom field assigned and displayed -and when the client enter some text-, it’s OK, but not in the rest of the products. What can I change in the code to solve that? Thank you!!!

Reply

Hi – you’ll need to add some code in the validation function to ensure you’re only validating products that have your custom fields.

Gareth

Reply

Hi Gareth!
Really appreciate your answer!! But maybe this is the whole point of the plugin? I mean it’s supposed the validation will be effective only on products that have custom fields, the validation must not make interference with other products that don’t have a custom field assigned, or the buying process at all. If you put this code “as is” then the “add to cart” button become useless (please try to see it in action).
Please, could you be so kind to give us a hint or maybe consider improving the current code??
Thanks again!!!!

Reply

Hi

The code is meant as a starting point for people. Unfortunately I can’t provide custom solutions on request for free.

Gareth

Reply

Hi Gareth, I really don’t believe anyone is trying to get things for free. Anyway, I wonder if you guys are aware that if you put this code the Store gets useless and the “add to cart” button will be deactivated (do nothing) without any clues for the front-end users? My intention is to contribute to improving this code. I’m wrong? Thanks again!

Okay, that’s great. I’m very open to your code contributions. Thank you.

Hi Gareth,
Thanks for your code!
But I have a problem with that. MiniCart ( woocommerce_mini_cart() ) show old value without changes. That’s because hook “woocommerce_before_calculate_totals” not load when minicart show. To solve this problem, I slightly changed your code:

function cfwc_before_calculate_totals( ) {
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) ) {
return;
}
$cart = WC()->cart->get_cart();
// Iterate through each cart item
foreach( $cart as $key=>$value ) {
if( isset( $value[‘total_price’] ) ) {
$price = $value[‘total_price’];
$value[‘data’]->set_price( ( $price ) );
}
}
}
add_action( ‘woocommerce_before_calculate_totals’, ‘cfwc_before_calculate_totals’, 10, 1 );
add_action( ‘woocommerce_before_mini_cart’, ‘cfwc_before_calculate_totals’, 10, 1 );

This code works fine for me.

Reply

Hey, awesome tutorial. I am wondering if there is a solution to hook the plugin elsewhere than at “woocommerce_before_add_to_cart_button”? I would like to place it at the position “woocommerce_after_single_product_summary” for several reasons, but it is not working obviously. Any hints on that are highly appreciated 🙂

Reply

You need to hook on woocommerce_before_add_to_cart_button so that the fields are part of the add to cart form.

Reply

Displaying custom fields when you “edit an item from the cart page”.

I can’t get the current item key from the cart. I was a lookup in the whole cart but I didn’t find how to retrieve the current item key or id for making a diff, after that when you come for edit item from the cart then the data is no available to show again in the customs fields.

Reply

You can use something like this to get item keys from the cart:


$cart = WC()->cart->get_cart();
// Iterate through each cart item
foreach( $cart as $key=>$value ) {
// ... Do something
}

Reply

Hi Gareth, thank you for the advice. In fact, I do that but I can’t do a difference with “the current item”. For example: if I have the same item with different custom field then the id_procut is the same one, the keys are different but I cannot choose which one is for each.

Reply

Hi Gareth,

Thank you for the amazing tutorial. Does your plugin work with variable products? I’ve followed every step and everything works fine until I get to “Calculating The Custom Price”, it doesn’t seem to add the correct variation price, only works with simple products. Can you please confirm? Thanks man, I’ll be eternally grateful!

Reply

Hi Gareth,

Just found the way to adjust it for variable products by changing the “wc_get_product” settings to “variation_id” instead of “product_id”. Again, thank you for this great tutorial, it works perfect.

Reply

Please let me know how can I add date picker with different date format as custom field.

Reply

Hi Gaurav

You can do this out of the box with the Product Extras plugin. Or you could enqueue the JQuery Datepicker plugin and add some script to turn the text field into a datepicker field.

Reply

Love that tutorial – thanks for your work!
I was wondering if it is possible to use it with variations, I already tried a lot of things, a lot is already working.

The custom fields are displayed and stored successfully in the backend.
But I’m struggling to use this for the specific variation – it always uses the values of the first variation…
Which is absolutely right, since I didn’t use the variation_id, but I don’t know how 🙁 Can you help?

Here is the necessary part of my code:
function cfwc_validate_custom_field( $passed, $product_id, $quantity ) {
$product = wc_get_product( $product_id );
$title = $product->get_meta( ‘custom_text_field_title’ );
$max_size = $product->get_meta(‘custom_text_field_max_size’);
$one_size = $product->get_meta(‘custom_text_field_1_size’);
$two_size = $product->get_meta(‘custom_text_field_2_size’);
$three_size = $product->get_meta(‘custom_text_field_3_size’);

Reply

Hello. Thank you for the info. I’m using your code to create a custom field in my site. 🙂
I just need to use the Custom Text Field Title to show that title in product page and in checkout page. I don’t need the field to the user can leave text.
Any idea how to achieve that? Thank you 🙂

Reply

Hi
how to hook the custom function woocommerce_product_options_general_product_data. as i can able to see the fields in backend in the product but but can not able to see the frondends.

kindly help me.

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *