WooCommerce: Add Custom Field to Product Variations

Adding and displaying custom fields on WooCommerce products is quite simple. For example, you can add a “RRP/MSRP” field to a product, or maybe use ACF and display its value on the single product page.

Easy, yes. Unfortunately, the above only applies to “simple” products without variations (or the parent product if it’s a variable product). So the question is: how do we add, save and display a custom field for each single variation?

WooCommerce: how to add a custom field to product variations

Part 1 – PHP Snippet: Add & Save Custom Field @ Product Variations

/**
 * @snippet       Add Custom Field to Product Variations - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 4.6
 * @community     https://businessbloomer.com/club/
 */

// -----------------------------------------
// 1. Add custom field input @ Product Data > Variations > Single Variation

add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 );

function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
   woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Custom Field', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
   ) );
}

// -----------------------------------------
// 2. Save custom field on product variation save

add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );

function bbloomer_save_custom_field_variations( $variation_id, $i ) {
   $custom_field = $_POST['custom_field'][$i];
   if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
}

// -----------------------------------------
// 3. Store custom field value into variation data

add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );

function bbloomer_add_custom_field_variation_data( $variations ) {
   $variations['custom_field'] = '<div class="woocommerce_custom_field">Custom Field: <span>' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
   return $variations;
}

Part 2 – WooCommerce Template Override: Display Custom Field Upon Product Variation Selection

As the variation selection process uses JavaScript in order to retrieve the correct variation data, the only choice we have is to override the WooCommerce template file called variation.php, which can be found under woocommerce/templates/single-product/add-to-cart

Please note – we won’t edit core files (because a) it’s not a great idea and b) code will be deleted next time we update WooCommerce). Instead, in order to override this template, we create a file called “variation.php” and place it in our child theme’s “woocommerce/single-product/add-to-cart” folder. If that doesn’t exist, create it via FTP.

The final child theme’s woocommerce/single-product/add-to-cart/variation.php file script should look like this (please note you must change “custom_field” occurrences in case you renamed it in Snippet 1):

<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">
{{{ data.variation.variation_description }}}
</div>

<div class="woocommerce-variation-price">
{{{ data.variation.price_html }}}
</div>

<div class="woocommerce-variation-custom_field">
{{{ data.variation.custom_field}}}
</div>

<div class="woocommerce-variation-availability">
{{{ data.variation.availability_html }}}
</div>
</script>

Is There a (Reliable) Plugin For That?

If you’d love to code but don’t feel 100% confident with PHP, I decided to look for a reliable plugin that achieves the same result (well, actually it gives you more).

In this case, I recommend the WooCommerce Custom Fields for Variations plugin. On top of adding any kind of custom field to variable products (text, textarea, select, checkboxes, or radio buttons), you can group them under separate headings and allow the shop manager to manage them more easily and much more.

But in case you hate plugins and wish to code (or wish to try that), then keep reading 🙂

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Custom Add to Cart URLs – The Ultimate Guide
    In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […]
  • WooCommerce Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: Show Number Of Products Sold @ Product Page
    WooCommerce database already stores the number of products sold for you. Therefore, you may want to show such number on the product page, close to the Add To Cart button. As we’ve seen in my book Ecommerce and Beyond, showing the number of sales for each product can increase your sales conversion rate. All you […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

155 thoughts on “WooCommerce: Add Custom Field to Product Variations

  1. Hello. Thank you for your code. I have a question if you can find to answer me. I want to use this custom field to add link for image that will then export it as main image only for facebook with ctx pro. I did it and everything are great. I want only this functionality (back end) so it is not required the variations php change right?

    1. Exactly! That’s only for showing the custom field value on the frontend

  2. Ciao Rodolfo!
    Thanks for your snippets.

    I’m trying to query the variations to display only the ones that contains a custom field (a checkbox).
    Do you know by chance where do I find the custom field in the database?
    I’m using this arguments for the query, but I don’t see the custom field in the array:

    $args = array(
                    'post_type' => 'product_variation',
                    'post_status'     => 'publish',
                    'posts_per_page'  => -1,
                    'post_parent__in' => get_variation_parent_ids_from_term( $cat_name , 'product_cat', 'name' ), // this is a function to get the variants
                );
    
      1. Yes, meta query did the trick! thanks

        'meta_query' => array(
                            array(
                                'key'     => 'show_field',
                                'value'   => 'yes',
                            ),
                        ),
        
  3. Hi,

    Thank’s for your snippets !
    But I need help here, when I export product table into cdv files, the custom field entry data is in the meta column ‘custom_field’ but I want that the data be in my Custom column, not in the meta ! Can you help me here ?

    Have a great day !

    1. Hello Mathis, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  4. Thank you very much for this.
    How do I show this field’s data on the order view of this in the admin section?
    Like if someone places an order for this variation, I want this field to show on the order, but only in the admin section.. I don’t want it emailed to the customer or to appear on any customer’s views…
    Much appreciated if you can point me in the right direction

    -Josh

    1. Hello Josh, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  5. Thank you for this article, I was able to add this relatively easily.

    My question is where do I find what the Custom Field is supposed to display? And once I’ve figured out what the code is, how do I write into this custom field?

    I’m trying to set up Xchange for Variable Products but I’m unsure of what I now add to this custom field section.

    Let me know, thanks.

    1. Hi Alex! Part 2 of the tutorial tell you how to display the value @ frontend. In part 1, also, and with the help of the screenshot, you can find out how to save new data into this custom field. Hope this helps

  6. Hello,

    how to add these custom fields on the cart and checkout page ?

    Thank you

    1. Hi there thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  7. Hi
    Can this create a Custom field on a Variation that then also downloads via the normal products export and can be edited via an upload?

    1. It should – if not, there is a way to add custom fields to the export files

  8. Hello Rodolfo

    Thank you very much for this code it’s great!

    I have a question please
    How can I display the result of this field only in the sheets of products on backorder ?

    Thank you so much for your help !!

    1. Hello Leo thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  9. still working mate,

    thank you so much

  10. This is a lovely piece of code. Would I be wrong in thinking that you could swap out the custom field for a custom post type? I’m thinking of a drop down or select2 field.

  11. Hi there, I have this working, and I’ve been able to customize it a little bit. But I’m wondering if the text inputs and text areas that can be created by this have the ability to output HTML content? For example, two of my variation fields need to have a ul list of items (bullet points are necessary) and one of the variation fields has a complicated table. Do you have any sources for how I could achieve this?

    1. Hey Laura, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

      1. I have a similar question, how could we adjust this snippet so that I can load a PHP script from these custom fields? I understand it’s custom work, but it wouldn’t be that complicated, would it?

        1. Hey Bouke, could you expand on that please?

  12. Hello there, some help to add the available product variations to the admin products list?
    I like to show all my “product” and also “product_variation” on my products admin list.
    Thank you in advance.-

  13. Thanks @RodolfoMelogli for saving a day. The Code does work, perfect. the custom field is saved but when I am calling it another filter hook so the value is not coming in custom function. I will be grateful if someone can help. Thanks in advance

    1. Hi Bilal, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  14. Thank you Rodolfo, the code works great.
    Are you familiar with a method (plugin/place with some code) to filter products by those fields?
    I can’t find any and it would be so helpful.

    All the best!

  15. Thanks so much for the snippet! A couple of notes:

    1. You might make it clearer that the variations.php override is only needed if you’re going to select products based on the variation. If you’re just using this snippet to save data to a specific variation (like a GTIN), you don’t need the variations.php override.

    2. If you add a ‘wrapper_class’ to the woocommerce_wp_text_input array, you can format the custom field to look a little nicer.

    1. Nice, thanks for your feedback Jason!

      1. At this case how we can display this data / If you’re just using this snippet to save data to a specific variation (like a GTIN), you don’t need the variations.php override.

        like I have a costum field with name barcode_number

        I try to show it with many ways but I cannot. How I can show it and make it as function in my child theme…

  16. Hi
    In there any way to expose those custom fields via REST API ?
    I do have an external system which gets product data from my Woo but seems those custom fields are not available via API.
    I did try this plugin https://wordpress.org/plugins/rest-api-custom-fields/ but does not work .. most probably because it uses v2 API but i need v3

    1. Hi Krzysztof, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  17. Hi,
    Many thanks for your great tuto !
    I need to break lines for my description so i used textarea instead of text to do it, but on the frontend everything go on on the same line, it’s not taking account of the line breaks of the field, can you help me ?
    Thanks !

    1. Hello Yohann, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  18. Hi Rodolfo, this is a great snippet, thanks!

    I realized that if I add data to the custom field in a variable product, and then after saving it I convert it back to a regular product, that the field then displays an array with all the old info.

    It would be cool if you would add a function that either clears the field or only gets the first value of the array, if the product type is changed.

  19. I have an advanced custom field in the product variation that I want to display in the additional information table in a new row under dimensions and one of my other attributes as per this guide article: https://businessbloomer.com/woocommerce-add-custom-field-product-variation/. I’ve managed to successfully create a new row in the product-attributes.php file – but now I am not sure how to pull in my custom field value to display in that table. Any suggestions?

    1. Hi Surendra, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  20. Hello Rodolfo,

    I was wondering if it is possible to show a product description (with embedded code like a youtube-Video, just as in the regular short or long product description of the product) for each variation. The regular woocommerce variation description seems to be very limited here)…

    Any help would be deeply appreciated!

    regards
    Hannes

    1. Hello Hannes, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

      1. Hello Rodolfo,

        Ok, thank you for your reply, of course I understand! In this case I found a workaround, however!

        best regards
        Hannes

        1. Great!

  21. Hi,

    I followed the code, however the variation custom field is not passed in the order. Is there more code to be added?

    1. It is passed to the order, but in order to print it you’ll probably need another snippet

      1. Which snippet would that be? How do I print the text field?

        1. Hi Ali, thanks so much for your comment! I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  22. Thanks for the great snippet!

    If anyone is looking to also add this field to the REST API orders, I’ve got a small addition to do just that, ‘step 4’ so to say. This code supports simple & variable products. (FYI; It uses the normal Custom Fields on simple products.)
    See the code below, you can just add this below the snippet provided in the article.

    // 4. Add the custom field to REST API orders
    function get_product_order_custom_field( $response, $object, $request ) {
     
        // Check if response has data
        if(empty( $response->data )) {
            return $response;
        }
    
        // Loop through all line items (products)
        foreach ($response->data['line_items'] as $line_item_key => $line_item_value) {
    
            // Get the Product ID (PID)
            $order_pid = $response->data['line_items'][$line_item_key]['product_id'];
    
            // Get the variation ID (VID)
            $order_vid = $response->data['line_items'][$line_item_key]['variation_id'];
    
            // Check what ID to use (0 = no varation)
            if($order_vid === 0) {
                // If no variation, use PID
                $meta_id = $order_pid;
            } else {
                // If there is a variation, use VID
                $meta_id = $order_vid;
            }
    
            // Get custom_field value
            $product_meta_custom_field = get_post_meta($meta_id, 'custom_field', true);
    
            // Catch empty fields
            if($product_meta_custom_field == "" || $product_meta_custom_field == false  || $product_meta_custom_field == NULL) {
                $product_meta_custom_field == "";
            }
    
            // Add custom_field value to response
            $response->data['line_items'][$line_item_key]['custom_field'] = $product_meta_custom_field;
        }
     
        return $response;
    } 
    add_filter( 'woocommerce_rest_prepare_shop_order_object', 'get_product_order_custom_field', 10, 3 );
    

    Hope this helps someone!

    1. Awesome!

  23. Hi Rodolfo!

    Thanks for the snippet, it worked perfectly for me πŸ™‚
    Now, I’m asking you for a quote because I’m afraid I need to go a little deeper. I need to integrate this field with an external application, and the developers are asking me to integrate the field into the product creation and modification webhook. Is it possible?

    Thanks!

    1. Sure, thanks!

  24. I did everything according to the instructions
    And does not work
    Anyway thank you very much

    1. Sorry to hear that! Works for me

  25. Is it possible to enable shortcode execution for meta field,

    1. Hi Muneeb, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  26. Bonjour je suis sous le builder Oxygen donc aucun theme, j’aimerais ajouter 5 champs personnalisΓ©s et les affichez sur mon front end de ma page produit oxygen

    Auriez vous une idΓ©es s’il vous plait ?

    1. Hey Brice, thanks so much for your comment! If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  27. Hello,
    The code is not working if I have 2 Variations Size & Type.
    working perfect if i have one Variation.
    do you have any solution ?

    1. Hi Tayssir, what’s not working exactly?

  28. Thanks for the code, Rodolfo! I would like to make the custom field a “select” type field. This code works for a text field just fine. Can you share how to make it a select field? Thanks.

    1. Hi Dave, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  29. Hi

    Although a little late to the field, but take note: do not use esc_attr but use sanitize_text_field when saving your field to the database. So The above code should be:

    // -----------------------------------------
    // 2. Save custom field on product variation save
     
    add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );
     
    function bbloomer_save_custom_field_variations( $variation_id, $i ) {
      $custom_field = $_POST['custom_field'][$i];
      if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', sanitize_text_field( $custom_field ) );
    }
    
    1. THANK YOU!

  30. Hello,
    Thanks for the code, it is almost perfect, but I have some trouble with it.

    If I edit my custom field in more variations (each variation has unique value) and then save changes, all variations has same value as last variation in list. I think values are overwritten somehow.

    Could you please give me an advice how to fix this?

    Thanks a lot.

    Eduard

    1. Hi Eduard, does that bug occur also when you switch theme and deactivate all plugins but Woo?

  31. thanks for this snippet !
    But If I want to display this field in email. how can i do that

    1. Hi Steph, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  32. How to show custom_field data below the product title in the product description page?

    1. Hi Pradeep, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  33. Good night, I’m trying to create a plugin to add a monetary value in the simple and varied product

    In the simple product, I retrieve the Value and display it in the product list, but it is not saved in the input in case of editing

    Problem 1: I am unable to cast the Value on products with variations and display the Minimum and Maximum Value in the product list

    Problem 2: I created the value column in wp_wc_product_meta_lookup but it is always ‘0.00’

    Sorry about my English
    Help me, please

    1. Edit: I think the max_value field was an error
      In theory, when the customer buys the shirt of price X, it can have a Value X
      or if you buy the Y price shirt, it may have a Y value

      1. Jonathan, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  34. Works great, thank you! One note, I had to add an array element in the add custon field function to get it to format correctly on the edit variations screen.
    ‘wrapper_class’ => ‘form-row’,
    Hope this helps someone else!

    function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
        woocommerce_wp_text_input( array(
            'id' => 'custom_field[' . $loop . ']',
            'class' => 'short',
            'wrapper_class' => 'form-row',
            'label' => __( 'Custom Field', 'woocommerce' ),
            'value' => get_post_meta( $variation->ID, 'custom_field', true )
            )
        );
    }
    
    1. Awesome!

  35. Hello, Thank you for the code, it works great.

    I’m a begginer and would like to know how can I add more than one custom field?

    1. Hey Lucio, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  36. Rodolfo you are a genius and very gracious to share your code. I have used this and other snippets of yours. This one included, they always are easy to understand, work seamlessly, and easy to implement. Thank you so, so much!

    1. Thank you!

  37. Hi, thanks for the snippet!

    I tried copying the snippet exactly how it is to functions.php, and I put the variation.php file in my child theme in /woocommerce/single-product/add-to-cart/ and the custom field saves correctly, but doesn’t display on the product page when I click a variation.

    Can you please confirm that this still works with the latest version of WooCommerce?

    Thanks!

    1. Yep, still works!

  38. Is it possible to display a text field, so the user can fill with some information?

    1. Hi Fred, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  39. Hi there,

    If I want to use this in conjunction with your MSRP snippet for regular products, should both custom field names be the same, or should they be different? For example, if I use “msrp” as my custom field name in your rrp code snippet, should I also use “msrp” as the custom field name with this snippet, if they are both used to display the msrp?

    Thanks!

    1. Hi Drew, I believe you can use the same name, but I’m not 100% sure. I’d need to test it but I have no time. Give it a go and let me know!

  40. I currently use CSV import suite to import a “delivery time” to a custom field for each product.

    Will i able to upload to this custom field using the above?

    I guess the field is known as “custom_field” but if i was to say add this in a csv with the product variation sku would it pick this up?

    Basically looking to sell tables and chairs and obviously depnding on colour chairs you select would change the delivery timebased on if we had stock or not.

    1. Hi James, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  41. Can someone confirm that this still works? Because I can’t get the data that I enter, to actually save.

    1. Thanks Rodolfo!
      You saved my day!

      It works like a charm πŸ™‚

      1. Great!

      2. Hi.are we to place the code directly without any editing in the required php files.
        Regards: Denison

  42. Hi Rodolfo;

    We are assuming to get special consultancy from you. We’r ready to pay you. Please contact me for project details related to woocommerce.

    Thanks in advance

    1. Hello Oktar, thanks so much for your comment! If you’d like to get a quote, feel free to contact me here. Thanks!

  43. I want to use this to create a custom field for a manufacturer part number (MPN#). Do I need to change the code so that instead of my new field being called “Custom Field” it will be called “Manufacturer Part Number”? Also, do I need to use one of the plugins for custom fields to create the new field as preliminary step to your steps?

    1. Hello Nolan! (1) Yes (2) No

  44. Is there a way to show variable custom field in shopping cart items?

    1. Hello Niels, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

      1. Yes it is possible, and it’s easy task

        $variation_id = $product->get_variation_id();
        $your_custom_field = get_post_meta( $variation_id , 'custom_field', true);
        

        By the way thank you Rodolfo for your snippet.

        1. You’re welcome!

  45. Hey!

    Thanks for this. Is it possible to make the custom fields display in the product-attributes tab? If so, how do I do this?

    1. Hey Dan, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  46. Hello Rodolfo. Thank you for your Snippet. But i have one question. Where i will void this snippet wherever in php code? I have a plugin for showing variation in grid gallery and i need to add result value from your snippet in php code (in different DIV) Thank you for your suppport

    1. Hi Peter, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  47. Hello, I am loving your tutorials, I was wondering if it is possible to a shipping class to the variations.php so the shipping class is displayed when variations are selected as the price or availability

    1. Not sure I fully understand, sorry

  48. I have added this code its works properly but how to display custom field data on single product page??

    1. Read Part 2

  49. Great!
    Is it possible to add also date and/or date range and venue als custom field?
    so u can make an easy event selling product without additional plugin.

    1. Yes of course πŸ™‚

  50. Hi and thank you for this great solution!
    How can I use the same method on a simple product page?
    Thank you.

  51. Hi Rodolfo,

    Snippet “Woocommerce add custom field product variation” works fine (but sometimes in some browsers custom_field dont show properly, but it works). Now we are looking for how to include these custom_field into woocommerce orders

    Do you have any idea how to do that??

    Thanks in advance
    Alvaro

    1. Hey Alvaro, thanks for your comment. Look for “custom field” onto this website and you’ll find similar snippets that also save order meta data. Hope this helps

  52. Hi,
    Do you have a plugin able to add variants to a variant of a product ?

    Here is an example of what I want to do.

    Let’s say I create a new shirt product with one attribute named Color where the values are: ColorParis, ColorVenise, ColorLondon. So I would ended up with 3 variants of the same shirt style: SKU – Color

    ShirtStyle-ColorParis
    ShirtStyle-ColorVenise
    ShirtStyle-ColorLondon

    The color names are color name given by the brand but they do not tell us anything about the real color then how can I add the real color name to the variant?

    If ColorParis is only Blue then I could simply create a new attribute to be able to select the real color Blue, but if ColorParis is a mix of White and Red, how can I select many colors for that variant ?

    Thanks

    1. Hey Denis, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  53. I have a query about this for Rodolfo or someone who may know.

    Is it possible to move the (custom field input ) to show *under the standard description input field – I think it would make it easier for a client/or anyone to find and understand.

    Anyone…..?

    1. Hey Roberta, thanks for your comment! You need to find an alternative to “woocommerce_variation_options_pricing” hook, maybe there is another one available for you that is positioned where you need it πŸ™‚

  54. Hello Rodolfo, this code did work a couple weeks ago, but now it does not display the values in the meta description on the single product page for variations. I can add and update the quantity and date fields and see the results of the changes in the meta data. The web page no longer shows the values of the fields.

    1. Hey Bruce, thanks for your comment! I don’t think Woo 3.5.1 changed the way this works, so try with some standard troubleshooting. Disable all plugins but Woo and switch theme, and see if it works.

  55. More edits – Forgive me if this may appear to be an overlong post – but it is beneficial. Also; I may repeat myself on occasion, but I want o be clear about all this.

    Using this code in previous versions of Woo resulted in nice variation descriptions. However, Woo has now implemented a “Description” field that does the same thing. ( Styling for this later )

    It supports html and is useful, but I wanted to use Bloomer code as well as the Woo, to add a second set of details pertaining to a particular variation. Seeing Woo has a global description, its easy to add it as a description – I wanted to have a separate set for particular items.

    The original Bloomer code has the div active at all times, so if there is no data entered it will still display – especially if there are colors, backgrounds, borders, etc applied. An additional “empty” style needs to be applied. This effectively “hides” the entire div and content if there is no content in the description two field.

    This required some changes to the Bloomer functionΒ code.
    Changes to the orig code:
    For the admin page, the “Custom Field” name was not working for the client, so a small re-edit was applied to make it more readable.

    Change 1 to:
    // 1. Add custom field input @ Product Data > Variations > Single Variation

     
    add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 ); 
     
    function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
    woocommerce_wp_text_input( array(
    'id' => 'custom_field[' . $loop . ']',
    'class' => 'short',
    'label' => __( 'Description <sup>2</sup> - Displays after primary description below &darr;', 'woocommerce' ),
    'value' => get_post_meta( $variation->ID, 'custom_field', true )
    )
    );
    }
    
    

    Then for the product page itself – some more changes to the function code ( uses the added styles primarily ) to display on the page. As mentioned before, if there is no data in the field, it simply does not show, nifty!
    Change 3 to:
    // 3. Store custom field value into variation data

     
    add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
     
    function bbloomer_add_custom_field_variation_data( $variations ) {
        $variations['custom_field'] = '<div class="woocommerce_custom_field no-data"><div class="var-desc2">' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</div></div>';
        return $variations;
    }
    
    


    Styling CSS
    – add to the child theme or wherever the styling for the site resides – possibly the customizer.

    This styles the woocommerce variation display area
    Please note: There is a font awesome badge icon preceding the text – remove if not needed

    /* variation description - woo default */
    .woocommerce-variation-description{
        display:block;
        background:#f2f2f2;
        padding:0px 14px;
        color:#006868;
        border: 1px dashed #666; 
    }
    /* variation two description - bloomer add */
    .var-desc2 {
        display:block;
        background:#f2f2f2;
        padding:18px 14px;
        color:#006868;
        border-color:#666; 
        border-left: 1px dashed;
        border-right: 1px dashed;
        border-bottom: 1px dashed;
    }
    /* variation description before icon - woo default */
    .woocommerce-variation-description p:before {
        display:inline;
        content: "\f02e \A ";
        font-family: FontAwesome;
        color:red;
        font-weight:300;
    }
    /* variation description before icon - bloomer */
    .var-desc2::before {
        content: "\f02e \A ";
        font-family: FontAwesome;
        color:red;
        font-weight:300;
    }
    /* hide div if empty - no content in field */
    .var-desc2:empty,
    .no-data:empty {
        display: none;
    }
    
    1. Nice πŸ™‚ Remember to wrap your code between shortcodes “php” and “/php”

    2. Thanks so much for this update Wolfgen! I was just struggling with how to hide this when I have no content in the custom field. However, since I’m using this to display a link to a PDF, the css hide function is not working, because there is content within the wrapping div.

      add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
       
      function bbloomer_add_custom_field_variation_data( $variations ) {
          $variations['custom_field'] = '<div class="woocommerce_custom_field no-data"><div class="technical-drawings-link"><a href="' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '" target="_blank">Click here to view/download Technical Drawing</a></div></div>';
          return $variations;
      }
      

      I need to be able to hide everything within the technical-drawings-link div if there is no content within the interior custom_field.
      Do you know of some way to make the hiding function work for this situation?

    3. Sorry about the late reply – lets see if I have this right?
      I showed how to hide the area if there is no content – however you do have content – a link to a pdf – right?

      Simply add a href link in the description field ( it supports html ) with a tip about it in the desc2 field

      …and you could change the function to show a link icon instead of the badge – f0c1

      it should work that way – you can alter the color of the link etc by adding a class to it, then referring to it in the css

  56. hello how did you find this hook woocommerce_variation_options_pricing I would like to put my field below variations SKU but can not understand which hook to use for it or how to identify hooks in admin, thank you

    1. Hello Mag – thanks so much for your comment! Just download Woo on your computer and do a file search for “woocommerce_variation_options_pricing”. You will find the right file and also other hooks if present πŸ™‚

  57. hey,

    How would you go changing variation price?

    as I done in single product ?

    function return_custom_price( $price, $product ) {
    	$shortcost_first = get_post_meta( $product->id, 'shortcost_first', true );
    	$shortcost_mid = get_post_meta( $product->id, 'vshortcost_mid', true );
    	$shortcost_minimum = get_post_meta( $product->id, 'shortcost_minimum', true );
    
    
       $unit_price = $shortcost_first +($shortcost_mid * ($shortcost_minimum - 1));
    	return $price + $unit_price;
        
    }
    add_filter('woocommerce_get_price', 'return_custom_price', 10, 3);
    add_filter('woocommerce_get_regular_price','return_custom_price', 10, 3);
    add_filter('woocommerce_get_sale_price','return_custom_price', 10, 3);
    
    1. Hey there, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

    2. thank you

  58. Awesome work! When trying to export product data via CSV or XML these fields do not appear. Are you able to suggest how to get them to appear?

    1. Hi there, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  59. Hi, can this also be used to add custom field which saves an image instead of text?

    1. Hi Jose, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  60. Hi…
    Amazing!!
    I have a question, how i can show the cutom field in the order item field??

    1. Hey Esteban, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  61. Hi Rodolfo Melogli

    If I want to change the customer filed to URL, how to do that?
    As I want to set a Variation to goURL function.

    thanks

    1. Hey Eddie, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  62. Hi

    In my theme this displays on the front end under the variation (size in this case) – I’d like it to display ABOVE the Price. I’ve toyed around and can’t get it to move at all! LOL.

    Is there a simple way to do this?

    Many thanks – works an absolute treat otherwise!

    1. Hey Ben, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

    2. I’d like to request/add another edit ing compound to this feature.

      Ive used this one with success to dispaly some extra info regarding the selected option, for example if the item has a Satin finish – that finish is UV treated. et, etc. – works well

      Is there a way to get this supporting html? Where a url or img link/popup be added to display an image to show just what that option is?

      EG Vertical, an image with a vertical dimanson – Horizontal an image with Horizontal dimensions – that way it could be used to display folding features or additional option popup links. Make sense?

      1. Hey Roberta, thanks for your comment! In part 3 of the snippet, whenever you echo the custom field content, you can definitely echo any HTML you like, including an image tag πŸ™‚

  63. This works with some caveats though
    1) if you change the label in the code from
    ‘label’ => __( ‘Custom Field’, ‘woocommerce’ ), to a lnger string, EG:
    ‘label’ => __( ‘Extra Information’, ‘woocommerce’ ), (this was done so the client understood what it was

    In the edit view the label is no long enough and truncates itself to a narrower area

    2) If you decide to not use a string in that custom field (I assume the data is being saved to the options.php) could not find it though (my guess is that it is serialzed data). Anyway it retians the previous input unless its overwritten by something else. So if you need to have it blank after you had something there, you need to add a space. Would be good if cleared itself, if no data was present.

    I found all this when I styled the resulting custom field info by adding a class to “class=”woocommerce_custom_field” – like: class=”woocommerce_custom_field xtra-info”

    A note of interest: How difficult woult it be to have the field display under the product description area above the add to cart button? I’m using this as a descriptor for each variations particular differences.

    1. Hey Roberta, thanks so much for your comment! I fixed issue 2) by adding “delete_post_meta” in the IF/ELSE – see revised snippet. In regard to your other request “display under the product description”… yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

    2. I figured it out through the themes setup – its using Visual Composer.

      In Visual Composer you can setup a “template” to use if you are using the same procedure over and over again – like the loop.

      So I made one and using the plugin addons; I simply “arranged” the page to the clients liking, and then used it via the Wocommerce settings as the singl product page display. I just moved the desc, price and other components int different positions.

      Worked for me.

  64. Any chance to get this as a plug-in? Thanks

    1. Hello Sebastian, thank you so much for your comment! Feel free to contact me privately and I’ll give you a quote for the work. Thanks πŸ™‚

  65. Is there a chance to display the value of this within the cart.php?

    1. Hey there, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  66. Hello Rodolfo,
    Thank you for the fantastic work your doing here. I just discovered your site and… goldmine!

    I want to use this snippet you wrote but inside a plugin. I will put this plugin on wordpress.org and so, I will not be able to manually create a template in the child theme.

    Do you know if I can have the template inside my plugin and then override the normal plugin. Or maybe unhook the call to the normal plugin and hook this one?

    Thanks in advance,
    Lucas

    1. Hey Lucas, thanks for your comment! I don’t specialize in plugins, so not sure here. Good luck πŸ™‚

  67. Thanks for this useful snippet! I’m sure this will come in handy for my upcoming projects.

    One question:

    I have seen this kind of variable – {{{ data.variation.custom_field}}} – quite often in different template files but don’t quite understand what it means. Do you have any resources that touch on this topic?

    Thanks once again for this post!

  68. Hi,

    WhatΒ΄s the end goal with this? Can you show an example?

    Ricardo

    1. Hey Ricardo, thanks for your comment! For example, you might want to add a RRP/MSRP for each variation – or maybe a custom field such as an expiry date πŸ™‚

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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