How to add WooCommerce custom fields to a product

Create and display custom fields in WooCommerce

In this post, I’m going to walk through the entire process of adding WooCommerce custom fields to a product. We’ll look at two types of custom fields:

  1. Firstly, input fields (also called product add-ons) like text fields, select fields, checkboxes, and so on that allow the user to enter additional, personalised information about a product
  2. Secondly, we’ll look at WooCommerce extra product data fields – custom fields that display additional information for your products.

We’ll also take a look at how you can use both types of custom field in combination, displaying extra product data depending on certain user choices.

Examples of WooCommerce custom fields

Let’s take a quick look at both types of custom field so we understand the difference.

Custom add-ons fields

The first example below shows a product page for a jewellery website. You can see that there are a number of extra fields, like ‘Add a name’ and ‘Add a charm’ where the user can enter their own information and make certain choices about the product they want. This is an example of the add-ons type custom field.

Example product showing WooCommerce custom fields

Extra product data custom fields

The highlighted area in the second example below shows extra product data fields that display additional information for a product.

WooCommerce extra product data fields

You can see in this example that there’s no user input – it’s simply additional content.

Article contents

During this article, we’ll look at how to add both types of custom field to a WooCommerce single product page. And we’ll look at how to do this programmatically and using a plugin so we don’t need to write any code.

Use the menu below to skip to the section that interests you most. By the way, if you want to know how to add a new WooCommerce product, take a look at WooCommerce Add Product – the complete guide.

Part one: custom fields

Part two: extra product data fields

WooCommerce custom add-on fields

Take another look at the product page below. As well as the standard WooCommerce single product page elements, like title, price, quantity and description, you can see some additional fields like ‘Add a name’ and ‘Add a charm’.

For this product, the customer can enter their own information and make their own choices about the final product. They do this through custom fields.

Example product showing WooCommerce custom fields

The first part of this post will cover creating and displaying the custom fields in a product page, adding the custom field data to the cart, and inserting the data in emails and orders.

We’ll examine what custom fields are in detail and why you might need to use them. Finally, we’ll look at two methods to add WooCommerce custom fields.

What are WooCommerce custom fields?

As I mentioned briefly above, custom fields include any kind of form field, such as:

  • Text field
  • Textarea
  • Dropdown/select field
  • Radio buttons
  • Checkboxes
  • File uploads
  • Date fields
  • Number fields

These fields would be displayed on the front end product page near the Add to Cart button. They give customers the opportunity to configure or provide personalised information for the product.

Typical uses for custom fields

If you’re wondering why you would ever need custom fields in your WooCommerce store, think about any of the following product types:

  • Monogrammed or branded clothing and apparel: e.g. any kind of personalised teeshirts, staff uniforms, merchandising, anything that requires a custom log
  • Personalised jewellery: e.g. bangles that can be engraved with a name or personal message, lockets that contain photos of loved ones, necklaces or bracelets with optional charms or stones
  • Build your own products: anything from create your own sandwich or pizza products, through takeaway menus, to configurable skateboards, computers or phones – any product that creates optional elements that the user can configure

There are many, many more products where you would need to use custom fields. If you’d like some more ideas, please check out my post on creating customisable products in WooCommerce.

What is the difference between custom fields and attributes?

But hold on, you might be saying. Doesn’t WooCommerce already give us the ability to add custom fields through attributes and variations?

Not really: any product in WooCommerce, whether it’s simple or variable, is essentially fixed. You add the description, the price, the attributes and those are always going to be the same for every customer.

With custom fields, the product is potentially different for every customer. If you are selling bracelets that can be engraved with a name, then each customer will be entering their own name. You can’t create attributes for that.

You can check out this article, if you’d like to learn more specifically about adding custom fields to variations.

Why add custom fields

For detailed information about personalised products, you can take a look at this article on 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:

Adding WooCommerce custom fields without coding

If you are looking for the simplest way to add custom fields to your product pages, then take a look at the WooCommerce Product Add Ons Ultimate 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.

Click the image below to view all the plugin’s features.

WooCommerce: Add a custom text field

Let’s go through adding a custom field using WooCommerce Product Add Ons Ultimate. We’ll look at:

  • Installing and activating the plugin
  • How to add fields in the back end
  • What the fields look like on the front end
  • How the store owner receives the custom field data in new orders

Installing and activating WooCommerce Product Add Ons Ultimate

When you buy WooCommerce Product Add Ons Ultimate, you’ll get an email with your licence key and a download link.

  • Click the download link and save the zip file somewhere on your computer
  • Go to the WP admin for the site where you want to install WooCommerce Product Add Ons Ultimate
  • Click Plugins > Add New then click ‘Upload Plugin’
  • Upload the file you save to your computer
  • Click Activate Plugin

WooCommerce Product Add Ons Ultimate is now installed and active on your site.

Add a custom field

With WooCommerce Product Add Ons Ultimate activated, you can start creating custom fields in products.

  • Go to the product where you’d like to add a custom field
  • In the Product Data section, click the WooCommerce Product Add Ons Ultimate tab
  • Click ‘Add Group’ then click ‘Add Field’
  • Choose the type of field you’d like to add from the ‘Field Type’ option
  • In the option below, I’ve selected a text field as the field type
WooCommerce custom fields - text input

On the front end, this is what it’ll look like:

WooCommerce custom fields front end

Note that WooCommerce Product Add Ons Ultimate adds some pricing information above the Add to Cart button. This shows:

  • The base price of the product
  • Any additional costs added through extra custom fields
  • The overall total that the customer will pay after entering custom information

You can configure these totals fields by changing their labels, just displaying the total price, or hiding them altogether.

Custom fields – extra parameters

Returning to the extra field in the back end, you can see that there are several additional options for configuring your custom field. There vary slightly depending on the type of field you’re adding but let’s look at some of the most common ones:

WooCommerce custom fields - text input
  • Field label: this is where you can create a label for your field
  • Field price: want to charge your customers for entering information in this field? Just add the price here. This will get added to the product price automatically
  • Required field: if you’d like to ensure the customer completes this field before adding the product to the cart, then check this option
  • Flat rate: by default, if the field has a price, it’ll be multiplied by the quantity of product added to the cart. So if the field price is $5 and the user adds 2x the product to their cart, the field cost will be $10. If you only want to charge for this field once, irrespective of the quantity in the cart, check the ‘Flat rate’ option
  • Percentage: check this field to make the ‘Field price’ field a percentage instead of a fixed value
  • Min chars: this is the minimum number of characters the user can enter into this field. Leave it empty if there’s no minimum
  • Max chars: the maximum number of characters the user can enter. Leave it empty if there’s no maximum
  • Price per character: check this option if you’d like to multiply the field price by the number of characters entered into the field
  • Default: enter a default value here if you’d like this to display to your customer

For further details on all the extra parameters available to all field types, take a look at the support articles here.

Viewing custom fields in the cart and order details

When the customer adds a product to their cart that contains one or more custom fields, the field values will be added to the product name. Take a look at the example below showing a radio button field, a text field, and an image upload field:

WooCommerce cart custom fields

The same data is passed through to the order. So if you’re the store owner, you can quickly view what custom extras to add to the product:

WooCommerce order custom fields

Adding custom fields the easy way

So that concludes the section on the easy way of adding WooCommerce custom fields to a single product page. You can find out more about the WooCommerce Product Add Ons Ultimate plugin here.

WooCommerce WooCommerce Product Add Ons Ultimate plugin call to action

Adding WooCommerce custom fields programmatically

If you’d like to find out more about coding custom fields from scratch, then read on.

In this section, I’ll include code examples throughout. By the end you will have learned to build your own custom field plugin for WooCommerce. The plugin will:

  • Create a custom field in the 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

What’s in this section?

This section is organised into the following parts:

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

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 adding the custom field to 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

The 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://pluginrepublic.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 );

WooCommerce extra product data fields

Okay, so we said there were two types of WooCommerce custom fields. We’ve covered the first type, add-on fields, in depth above. Let’s now look at the second type of custom field: extra product data fields.

Let’s have another look at the screenshot from the start of the article. Or you could view the actual working demo here.

WooCommerce extra product data fields

Here you can see that we’ve presented the user with some further information about the product. In this case, it’s technical information but you can use custom product data fields for all kinds of purposes, including:

  • Technical specifications
  • Nutritional information for food products, e.g. calorie content, fat content
  • Additional notes about pricing
  • Product data that works best in a table format
  • Custom pricing information

How to add WooCommerce custom product data fields

It’s really easy to add WooCommerce custom product data fields. We’re going to use the ‘Information’ field type in the Add-Ons Ultimate plugin.

This image has an empty alt attribute; its file name is wcpaou-cta.png

Start by following the guidance above on adding custom fields. When you’ve installed and activated the plugin, you can add an extra field to your product.

Add an ‘Information’ field

From the Product Add-Ons section in the Product data panel, click ‘Add Field’. Choose ‘Information’ as the ‘Field Type’.

You can add multiple rows, entering a label and data in each. When you’ve added all the information that you need, you just update the product.

On the front end, the extra product data fields will be displayed in a table format like this:

You can add as many extra product data fields as you like.

WooCommerce custom data fields with conditional logic

So, you might remember way back at the start of this article, that I mentioned using both types of custom field together: WooCommerce add-ons fields and extra product data fields.

We can do this by setting conditions on our extra product data fields so that they are only displayed when the user has made certain other choices from the custom fields.

Take a look at the demo product again. You’ll notice that the custom product data fields under the ‘Processor’ field change according to which processor the user has selected.

Adding conditions to extra product data fields

There is a much longer article on conditional logic here but the basics are simple:

  1. Click ‘Add Condition’ for the field where you want to add a condition – in this case, to our information field
  2. Choose ‘Show this field if’ in the first select box
  3. Add your conditions one by one

You can see this in the screenshot below:

This means that this field will only display if the user has chosen the product with the ID of 566 in the ‘Processor’ select field.

Further reading

Here are a couple of other articles you might find useful:

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 WooCommerce Product Add Ons Ultimate plugin for extensive extra functionality.


Popular Posts

46 thoughts on “How to add WooCommerce custom fields to a 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!

Reply

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

Reply

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

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

Hello Gareth,

First of all thanks for this great article, everything is explained in detailed.

I am having an issue, the products on our site are marked as “Sold individually” as you can see here in the screenshot: http://prntscr.com/m0oefm

So when we try to add the same product with different custom field values, they are adding screenshot: http://prntscr.com/m0ogkw . I want to restrict it to allow only buy a single product with any custom field value, no same products with different values.

Can you please guide me how i do this?

Reply

Hello,

I have customized the “cfwc_validate_custom_field” function to limit product purchase.

—-

Now, I am trying to add this custom field in product loop on shop page.

By adding this hook along with the existing
add_action( ‘woocommerce_before_add_to_cart_button’, ‘cfwc_display_custom_field’ );
add_action( ‘woocommerce_after_shop_loop_item’, ‘cfwc_display_custom_field’, 9 );

The field is now appearing in product loop and product single page.

But when i try to “add to cart” this product from loop with custom field filled, its not passing this field data and gives error that custom field is empty.

Reply

Hello,
I wanted to pass the field value to the order details page without showing it on the front end but it didn’t work, is it possible?

Reply

Hi Gareth,

Your code worked but it’s missing one little detail.

When you go to checkout, the field and its value are shown, but when you are in the cart they are not. At least that’s the behavior in my implementation. Can you confirm this?

Thanks!

Reply

Dear Gareth,

first of all thank you for this awesome article, it helps me a lot and i did a lot of research to find this article :-).

I am having an issue, the products on our site are marked as “Sold individually”.

Can you please guide me how i do this? Is there any update coming soon?

Reply

Hi Gareth, thank you so much for this great post, it’s very helpful for who like me is just coming around Woocommerce!
I have a question for you as I’m having troubles with it.
I need to know if the user has bought a product with a custom field == a given ID.
To be precise, the given ID is the ID of the current post, so get_the_ID().
And the custom field of the products is, let’s say, “id_rel_post”.
How can I make the same research but checking if the custom field of the product matchs and not the id of the product?
Thank you so much!!!

Reply

Hi Lia – if you’re using the custom code above, you can use something like this:

$product = wc_get_product( get_the_ID() );
$field_value = $product->get_meta( 'id_rel_post' );
Reply

Thank you for this great tutorial. I would like to retrieve the value of the custom field on the product page, when we click on the product on the cart page. To prevent the user from re-entering it. In the url I can see the attributes (…/? attribute_pa_color = green& attribute_pa_taille = l) but not the value of the custom field. An idea of how?

Reply

On the cart page, you could use the woocommerce_cart_item_permalink filter to add your custom field as a parameter to the product link.

Then, on the product page, you’d need to use $_GET to retrieve the value of the parameter and populate the field.

Reply

Hi Gareth,

thanks for this in-depth tutorial. Is it possible to show the custom field information only in the confirmation email or on the Thank You Page and not on the product page?

My customers should get a link with every product which they should see after the purchase. The link is unique with every product type. I thought maybe I could include the link as a custom field and then hide it at the shop itself and display it in the confirmation email?

Would be awesome if the plugin could help me out. Thanks for your support!

Best regards,
Phil

Reply

Hi Phil

Yes, you could do this. The simplest way would be to use some CSS to hide the field on the product page.

Reply

Hi,

Thanks for this info. I have an issue I cannot get it to save the select value. This is what I have.

I hope You can help me out.

Greetings,
Robin

function cfwc_create_custom_field() {
  $args = array(
  'label' => __( 'Producttype', 'ctwc' ), // Text in Label
  'class' => 'select short custom_shipping-type',
  'style' => '',
  'wrapper_class' => '',
  'value' => '', // if empty, retrieved from post meta where id is the meta_key
  'id' => 'custom_shipping-type', // required
  'name' => '', //name will set from id if empty
  'options' => [
            'Eigen product' => __( 'Eigen product', 'ctwc' ),
            'Probo (klein)' => __( 'Probo (klein)', 'ctwc' ),
            'Probo (lengte)' => __( 'Probo (lengte)', 'ctwc' ),
            'Probo (volume)' => __( 'Probo (volume)', 'ctwc' ),
        ],
        
        
  'desc_tip' => 'true',
  'custom_attributes' => '', // array of attributes 
  'description' => __( 'Selecteer type.', 'ctwc' )
);
	woocommerce_wp_select( $args );
}
add_action( 'woocommerce_product_options_shipping', '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_shipping-type'] ) ? $_POST['custom_shipping-type'] : '';
	$product->update_meta_data( 'custom_shipping-type', sanitize_text_field( $title ) );
	$product->save();
}
add_action( 'woocommerce_process_product_meta', 'cfwc_save_custom_field' );
Reply

I would try removing this line:

'name' => '', //name will set from id if empty
Reply

Hi, I’m trying to implement your code but I prefer to display the input field inside the cart page, there is a way to do that?

Right know I just change this

add_action( ‘woocommerce_after_cart_item_name’, ‘cfwc_create_custom_field’ );
//add_action( ‘woocommerce_product_options_general_product_data’, ‘cfwc_create_custom_field’ );

Thanks in advance

Reply

Hi there. This article is all that I need for what I have to achieve. But, I cannot figure out where does the “cfwc-title-field” in %s come from? This lack of understanding is actually preventing me to display more than one custom field.

Reply

cfwc-title-field is the name and id of the custom field added in the code examples above.

Reply

Leave a Reply

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