WooCommerce Custom Fields for Variations

A few months ago I wrote a post on how to add custom fields to WooCommerce products within the administration, and many of you ask me how to add custom fields to products variations. So I decided to write this tutorial to help you create new fields for each WooCommerce product variation. The final result of this tutorial will look like this:

[box type=”yellow”]The code has been updated for WC 2.4+ If you need compatibility for WC < 2.4 use this code instead, Thanks ;-)[/box]

[box type=”yellow”]WooCommerce 2.5 introduced a new way to display variations custom fields values using wp.template. The code has been added below.[/box]

[box type=”blue”]If you want to add custom fields to products, read this post.[/box]

woocommerce-variations-custom-fields

Hooks

To achieve this, will need to create 3 functions: a first one to register the fields, a second one to create the fields when you click on “add variation” (javascript purpose), and a last one to save the fields data within the database.

Each function will be hooked to these specific actions:

  • woocommerce_product_after_variable_attributes
  • woocommerce_save_product_variation
  • woocommerce_product_after_variable_attributes_js
  • woocommerce_process_product_meta_variable

Fields Types

I will cover only 6 fields types for the moment, and I will probably create a new post for advanced fields later. In this tutorial, you will learn how to add these custom fields to variations:

  • Text Field
  • Number Field
  • Textarea
  • Dropdown Select
  • Checkbox
  • Hidden field

 A quick explanation

Basically the method is more or less the same what i explained in my previous post regarding custom fields for products, but in the case of variations, there’s something different that you need to take into account: when you click the “add variation” button, a new div is loaded by a javascript bit of code. The consequence is that when you register fields for variations, you need to register them twice, once for the “regular process”, and one for the javascript method. That’s why we use the two hooks: woocommerce_product_after_variable_attributes and woocommerce_product_after_variable_attributes_js.

Since WooCommerce 2.4+ you can now define only two hooks, and there is no need to register fields for javascript use anymore!

The code

Registering fields is pretty basic as you see we use the WooCommerce builtin functions (All these functions are located in WooCommerce/Admin/WritePanels/writepanels-init.php.):

Finally, the only “tricky” part is the within the save_variation_settings_fields() function, where you need to make sure that each field uses the update_post_meta() function, otherwise your field won’t be saved. The use of a “for” loop is needed to loop through all variations.

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

Displaying Fields Values on the Frontend with WooCommerce 2.5+

WooCommerce introduced wp.template, and it’s now easier to display variations custom fields values based on the selection of the attribute value in the dropdown select. You need to add the following function to functions.php:

And now you need to edit the custom template that display the variation fields. This file is called variation.php and is located in wp-plugins/plugins/woocommerce/templates/single-product/add-to-cart/. Do not edit this file directly but instead, duplicate it and place it in a folder called woocommerce/templates/single-product/add-to-cart/ in your theme folder (Keep in mind: never edit core files). Add this code:

Result:

wc25-variation-custom-fields

Thanks to Caleb Burks & Nicola Mustone for the update ;-)

218 responses to “WooCommerce Custom Fields for Variations”

  1. Guillermo

    Hi Remi,

    Thanks for the awesome post. This is really great. Im stuck on something right now though. Can you help me out?

    In summary, how do I get and display the value of the same custom field as a product variation is selected?

    Much like the price changes when the a different variation of the product is selected, I would like to conditionalize additional information within the div.single_variation_wrap based upon the value of a custom field for that product variation. I only have one set of attributes and thus only one drop down.

    So… if it was a text field, the text that is displayed would change according to the variation selected from the product variation drop down.

    Can you give me any insight into this?

    Thanks Remi.

    1. i’ll add a post on this very soon

      1. Guillermo

        Hey Remi,
        I figured out a way to do this. That is, dynamic content per product variation selected. I wrote about it here:

        http://blueskysessions.com/2014/03/31/woocommerce-display-dynamic-content-per-the-selected-product-variation/

        What do you think? Your feedback, any kind, is welcomed.

        1. That’s a really good post!

      2. Twansparant

        Hi Remi,

        I would like to achieve the exact same thing as Guillermo, but I’m having difficulties understanding how I can achieve this.

        If you look in the plugin’s file:
        woocommerce/assets/frontend/add-to-cart-variation.js on line 181 the value in the hidden:
        (inside the single_variation_wrap div) gets updated with the selected variation_id.

        In that same js file, all the selected variation fields get updated. We have to somehow hook into this function or make a own listener’s event with ajax.

        I gave it a try with this listener:


        (function($) {
        // Only on single product pages
        if ($('body').hasClass('single-product')) {
        $('.variations_form input[name=variation_id]').bind('change', function() {
        var variation_id = $(this).val();
        if(variation_id){
        jQuery.ajax({
        type: 'POST',
        url: $('#js-ajax-url').val(),
        data: {
        action: 'get_variation_id',
        variation_id: variation_id,
        },
        success: function(data, textStatus, XMLHttpRequest){
        //append results
        if(data){
        $('#js-variation-desc').html(data);
        }
        else{
        $('#js-variation-desc').html('');
        }
        },
        error: function(MLHttpRequest, textStatus, errorThrown){
        alert(errorThrown);
        }
        });
        }
        });
        }
        }) (jQuery);

        In the product-attributes.php template file I added the following after the product dimensions:

        <input id="js-ajax-url" type="hidden" value="/wp-admin/admin-ajax.php" />

        And in my functions.php I added the following function:

        function get_variation_id(){
        $var_id = $_POST['variation_id'];
        // get the data from the custom fields
        $diameter = get_post_meta( $var_id, '_custom_field_1', true );
        $capacity = get_post_meta( $var_id, '_custom_field_2', true );
        die($var_id);
        }
        // create custom Ajax call for WordPress
        add_action( 'wp_ajax_nopriv_get_variation_id', 'get_variation_id' );
        add_action( 'wp_ajax_get_variation_id', 'get_variation_id' );

        Which updates the selected variation id correctly. So from there you can retrieve all your custom variation fields and display them!

        However there is a big delay of a few seconds… Isn’t there a faster way? Any ideas?

  2. […] Speaking of WooCommerce, here’s part 2 of the developer series from Max Rice we’d mentioned last week: Get and Update Order Information, and a tutorial from Remi Corson on creating custom fields for product variations. […]

    1. tsutton

      Hi, Remi!

      I am wondering if you have any ideas how to accomplish this…
      I am wanting to use WooCommerce for a golf outing fundraiser. I originally wanted to do this to collect payments so there wasn’t so much cash and checks at the fundraiser. If someone were to purchase a foursome team entry for the outing, how can I collect the four player’s information? Is there a way to force a customer to a form that will allow them to enter a team name and the name, company, address, and phone number for each player as a registration for the team?

      I bet this is something that many people could use for this exact purpose.

      1. jammermass

        hey there,

        I have the same problem.

        I am trying to setup a site to handle conference ticket purchasing. When the user selects more than 1 ticket to buy, ideally custom required fields (Name, Email) would appear for each additional ticket. This way all the attendee info would be collected. Then, how cool would that be if the Name/Email info. generated a new user in the system. I am dreaming that someone might respond to us with a solution.

  3. ivendo

    All i want is a single line text-input on a single product page so visitors can let me know what the want to print on a product (custom input). Is this posible with your code? And how? Can you give me the steps to take? Kind regards.

    1. sorhaug

      Did you find out about this one? I am looking for the exactly same thing.

      1. soccergrl

        I know this code won’t create a fillable text box on the front-end, but has anyone figured out how to do this yet? Without buying a plugin?

  4. Olajimmy

    Hi Remi, I have been avid admirer of woothemes and woocommerce. I need a custom quote with both conditional logic and relational fields for an insurance product based on my findings non of woocommerce extension can actually do exactly what i want. Then i used gravity form for the quotation and bought the extension for gravity form to woocommerce product. having done this, i was able to take the product price to woocommere checkout page. Here is the problem that i have now- i will like to export some fields from the gravity form to woocommerce checkout custom field (i currently use chekout editor but do not mind dropping snippets in my function.php) page and make it uneditable. can you please help me in this regards? Or is their a better way to go about it?

  5. whoaloic

    Hi Remy!
    I don’t know how to get those values on the frontend.
    What is the ID of the field “_textarea” in your example ?
    I try get_post_meta( $post->ID, ‘_textarea[ + loop + ]’, true ); or get_post_meta( $post->ID, ‘_textarea[ ‘.$loop.’ ]’, true ); or et_post_meta( $post->ID, ‘_textarea”, true );.
    None of those is working.
    Could you please explain me on this?

    1. Guillermo

      whoaholic,

      I wrote a short tutorial on how to display custom field data for each product variation. Maybe it can give you some insight on how to show the data on the frontend.

      http://blueskysessions.com/2014/03/31/woocommerce-display-dynamic-content-per-the-selected-product-variation/

      1. Kahil

        I’ve tried following your example and no matter what I do, it simply won’t display on the front end. I’m not editing a core woocommerce file, but I am simply trying to pass it through a hook in my functions.php file. I’ve done this many times with other scenarios, but this simply isn’t working and I can’t figure out why. Any ideas or a working snippet that takes the value from the backend and displays it on the frontend using the functions.php file and hooks?

        1. Willem-Siebe

          Did you managed to do this Kahil? I’m not succeeding as well.

  6. viky081

    Hi Remi,
    I tried to use the checkbox in variations. I tried your code looks like saving is not the problem but when i uncheck and save still the checkbox is checked i am not sure where is the problem i am using the recent version of woocommerce. Can you please look into that and give me a suggestion would be great :)

    Thanks,
    vicky

    1. mcmedia79

      I have the same error here as viky081

      1. mcmedia79

        Here’s the code for the checkbox to modify in the save function :


        $olddata = get_post_meta( $variable_post_id ,'_checkbox', true );
        $curdata = stripslashes( $_checkbox[$i]);

        if( $olddata == "" && $curdata != "" )
        add_post_meta( $variation_id,'_checkbox', $curdata );
        elseif( $curdata != $olddata )
        update_post_meta( $variation_id,'_checkbox', $curdata, $olddata );
        elseif( $curdata == "" )
        delete_post_meta( $variation_id,'_checkbox' );

  7. […] I am trying to find the solution of get the custom field variation data in a front end. I am not sure how to get the variation id on changing the list box of variation product. For example variable product as color contain red, blue, green. I added the custom field for all the color combination. Here is the code that i tried with credit(http://www.remicorson.com/woocommerce-custom-fields-for-variations/) […]

  8. janestone08

    Hi Remi,

    I’d like to add some custom text fields for users to input some necessary message like the following and have them displayed on the order list in admin dashboard:

    Item Price Quantity Total Notes
    ———————————————————————————————————–
    Product A $10 1 $10 “custom text fields”
    Product B $5 1 $5 “custom text fields”
    Product C $15 1 $15 “custom text fields”

    Can you pls advise how I can make it? Any extension?

    Thanks a lot!!!

  9. joehudson

    Hey Remi, Would this work to make a hidden attribute too?

    I have a tshirt shop and there is information needed for my printer that should not be seen my my customer. IE: Tshirt Model: Gildan 2000

    I was going to use http://docs.woothemes.com/document/woocommerce-customer-order-csv-export-developer-documentation/ to export the orders for my printer and need to figure out how to simply include the hidden info too.

    Maybe this code will work, if not do you know of a simple solution to do this?

    Thanks man! Great blog!

    1. yeah that could work! ;-)

  10. siemcreator

    Hi,

    I was building a HOTELS site. I want to make variation for all saturday of the year and some special days with different price.

    Can you help me for this issue?

    Thanks you so much!

  11. patgilmour

    I got this working great but now I’ve lost a day trying to incorporate the cool “Products Select Field Type” from the first tutorial in this series into Variable Products.

    I suspect I need to change:

    $product_field_type_ids = get_post_meta( $post->ID, '_product_field_type_ids', true );

    But I’ve tried everything I can think of. Any pointers?

    Thx

  12. Jeremy

    Hi Remi,
    Thank you for this fantastic post. I just had a quick question regarding WooCommerce Importing Suite: How would we get the variation custom fields to import via a CSV?

    Thank you for you help and insight!

    1. Using the “meta” method explained in the plugin docs ;-)

  13. me8him

    Hello Remi,

    Great bit of code! I’ve got it in. All i needed was an input field so I deleted all the other bits, select etc.

    For some reason it is showing a bugging error: Undefined index: _text_field

    for the line: ‘value’ => $variation_data[‘_text_field’][0]
    in => woocommerce_wp_text_input
    of => variable_fields

    When I tried it without deleting anything I was getting the same errors on each field as well. Any ideas?

    Great site by the way, lots of fantastic little snippets which has help me along the way! Keep it up!

    Josh

    1. dademaru

      Hi, I have the same issue with WP 4.1.1 and WC 2.3.4

      Also, even using only the text_field, when I update the product the entered value is not saved.
      Is this related to WC 2.3.x?

      How to fix the “Undefined index” notices?
      With all the custom fields enabled I get all the notices close to each custom field, and when updating the post I get the notice for the checkbox field + “Warning: Cannot modify header information – headers already sent by (output started at…”

      Thanks
      Dade

      1. Will check with WC 2.3+

        1. whoaloic

          Same issue. My custom fields for variations don”t save.

        2. Alessandro Marchetto

          Some time ago someone put a comment about and … undefined index: _ (all new custom field)
          I have same problem with last wp and woo version
          On february 2015 you answer i will check with 2.3+

          the error is related to this line for each of the custom field
          ‘value’ => $variation_data[‘_text_field’][0]

          di you find a solution ?
          Thanks a lot
          Alex

          1. Alessandro Marchetto

            Here again, SOLVED, maybe with 2.3.8 something is changed.
            I modify your code like this :
            // Text Field am_minimun_quantity
            woocommerce_wp_text_input(
            array(
            ‘id’ => ‘am_minimun_quantity[‘.$loop.’]’,
            ‘label’ => __( ‘Min. Qty’, ‘woocommerce’ ),
            ‘class’ => ”,
            ‘wrapper_class’ => ‘form-row form-row-first’,
            ‘placeholder’ => ”,
            ‘description’ => __( ‘Entern minimun Quantity to be sell of this product.’, ‘woocommerce’ ),
            ‘value’ => get_post_meta($variation->ID, ‘am_minimun_quantity’, true),
            ‘type’ => ‘number’,
            ‘custom_attributes’ => array(
            ‘step’ => ‘1’,
            ‘min’ => ‘0’
            )
            )
            );

            It was not true that data are not saved, with phpmyadmin i checked the post meta and all data are writed, but not showed on the products variation.
            To solve this is enought change your code on value for all new custom field, from :
            $variation_data[‘name_of_the_field’][0],
            to:
            get_post_meta($variation->ID, ‘name_of_the_field’, true)
            And everything start work like remi said.
            I also changed the save function so is faster and shorter.
            In $array_custom_field i put all my custom field.

            /**
            * Save new fields for variations
            *
            */
            function save_variable_fields_new( $post_id ) {
            if (isset( $_POST[‘variable_sku’])) {

            $variable_sku = $_POST[‘variable_sku’];
            $variable_post_id = $_POST[‘variable_post_id’];

            // all my custom field array
            $array_custom_fields = array(‘am_minimun_quantity’,
            ‘am_maximun_quantity’,
            ‘am_one_for_each’,
            ‘am_quantity_to_request’,
            ‘am_optional_field_1’,
            ‘am_optional_field_2’,
            ‘am_optional_field_3’);

            foreach ($array_custom_fields as $custom_fields) {
            $_custom_field = $_POST[$custom_fields];
            for ( $i = 0; $i

            Hope could be useful
            Bye to All
            Alex

          2. clydet

            Hi Has anyone found a solution for this yet?

  14. marktait

    Hi Remi.

    Do the changes above, effectively give you the same functionality (ie. in my case all I want to do is add a free text box on a variable product) than the Product Add-ons plugin WooCommerce sells?

    All the best, Mark

    1. No, the code I provide doesn’t create fields on the frontend.

  15. parkinep

    Hello and thank you for this article! Have there been any significant updates to woocommerce since the time of writing as I am getting errors trying to add new variations Like this. It also seems as if the second function “variable_fields_js” is never called and it uses the first one to generate the fields for the new variation.

  16. ravi.kulkarni

    HI all,
    As I am new one to the WP can any one tell me on which file of latest version of WooCommerce 2.1.8 shall I add these code/hook.Please give me full path to add these code for admin site display variation and also provide code and file path to display it to the user.
    As path provided here is ‘WooCommerce/Admin/WritePanels/writepanels-init.php’ not there on new version.
    Hope positive response form you.

    1. You must not edit WooCommerce files. Use the functions.php file in your theme folder.

  17. sandeep

    While I am adding the “New Fields” code in functions.php I am getting the error “Notice: Undefined index: _textarea in /home/xxx/public_html/wp-content/themes/canvas/functions.php on line 102” above the fields in variations.

  18. satmadrid

    Hello, i want a code for create text-field for clients
    Like https://www.woothemes.com/wp-content/uploads/2011/11/Screen-Shot-2013-05-23-at-13.46.00.png

    (“the text field”)

    search in your code but i cant find, you can help me? thanks

  19. hanshansen

    Hi Remi,

    i used the Code like it is – it will be saved, but i can’t Display it on the Frontpage. With the “the_meta()” i don’t get any results of it.
    Do you have an idea for me?

    thanks,
    hanshansen

  20. rekowsky

    Hi Remi!

    Thanks for this post!
    I managed to add the custom field variation for my website and extended it a bit because I have many variations for different product types.
    I still do a have a question to personalize the cart, order and e-mail form to retrieve the custom fields I have for the variation.

    When I check the received order I see the correct sku number since it is part of the default variation fields for woocommerce.

    I added an extra text for description and a barcode number (textfield). How can I retrieve the custom textfield for variations and show the result under cart, order and email?
    Thanks!

    1. Using get_post_meta().

  21. Jay

    This code looks like it’s just what I needed, thanks! However. I am having trouble displaying the information stored in my custom text field.

    I would like to show this info along with the other product attributes like weight and dimensions in the ‘Additional information’ tab. The problem is that using “get_post_meta()” gets me a string with all values from each variation, instead of showing just the active variation’s value. Any thoughts on what I should do to get this field to behave like the others? Thank you.

    1. tysanne

      Hi Jay and Remi,

      Any luck with that ? We are trying to do the same thing !

  22. magmatrix

    Hello Remy!

    I am using WooCommerce Measurement Price Calculator, but i need to add a base price to each variation.

    Is it possible to make a custom numeric field called “Extra cost” and have that added to the normal price?

    I.e. like a “price filter” which takes the ordinary price of the product and just adds the “Extra cost” price?

    Thanks!

  23. gx2g

    I see on the other page you use this to populate it on the front end.

    ID, ‘my-field-slug’, true );

    // You can also use
    echo get_post_meta( get_the_ID(), ‘my-field-slug’, true );
    ?>

    I’m trying to show just the textarea field on the single product page. can you give me the echo for that and also where do I put this in my woo theme folder? I’m having trouble with that. I’m a new comer. please help me.

    1. Apparently your snippet was cut-off

  24. rene

    Hey Remi,

    do you know how to add the values from the variations custom fields to cart.php? I know usually you just would answer by “using get_post_meta(); ” and it would look something like this:

    $key_1_value = get_post_meta( $variation_id, ‘_textarea’, true);

    Sounds simple but within the loop of cart.php I just cant’t find a way to get the variation ID.
    If I use “get_the_ID();” it will return e.g. “3040”, which is the product ID.
    There is also a variable called “$cart_item_key” but this is looking something like this: 5bb41674cdc46625a906b69930706f01

    I would really appreciate your help with this, since I can’t find a answer anywhere in the web.

    Thanks so much!

    1. oococc

      $var_id = $cart_item[‘variation_id’];
      echo get_post_meta( $var_id, ‘_short_description’, true );

  25. robertfranksargent

    As far as I can tell the save hook does not work for Subscription products. Has anyone found a fix?

      1. robertfranksargent

        I managed to get it working by adding the following action not included in the original code:

        add_action( ‘woocommerce_process_product_meta_variable-subscription’ , ‘save_variable_fields’ , 10 , 1 ) ;

        1. This does work! Thanks @robertfranksargent. Is there a way to have this custom field show up on the Order page?

          What I’m doing for each variation is provide an option for shipping cycle — monthly and every other month. In the order, it simply needs to show up like a key => value pair you know? Like Shipping Cycle: Monthly.

          I have the data saved to the subscription product. Now, to have it show in the Orders!

  26. nicksarr1

    Hmm why can’t i seem to find this file in my woocommerce folder?

    1. it’s in your theme’s folder.

  27. nicksarr1

    Can anyone help me find where i edit the file? I don’t see the admin folder or the file anywhere?

      1. nicksarr1

        I pasted the code in my functions.php in my theme folder and I do see the field appear in my variation on the backend, but on the frontend It won’t appear when the variation is selected? I’m not sure what to do?

        My Theme isn’t a woocommerce theme so I don’t have a woocommerce folder in my theme. The woocommerce plugin does how ever work well with my theme. Not sure if that matters at all?

        1. the code I provide here is just to create fields in the administration, not on the frontend.

  28. nicksarr1

    Can any one help me with this? I got the field to appear when I edit a product variation, but I can’t get it to show on the front end?

  29. mweigand

    Hi Remi,
    thanks for your great snippets. I just used it in a project and it worked right out of the box.

    One question: Is it possible to re-order the fields so that a custom field i.e. shows directly after the selling price?

    Thanks in advance

  30. fakeartist

    Hi. Excellent article. One question / bug though. For checkboxes If I leave the if condition

    if ( isset( $_checkbox[$i] ) ) {

    }

    then I cannot uncheck the value. If I remove it it works fine. It is unnecessary right?

  31. stankovich

    Hi Remi ,i like your page, im not a coder.))) and i really need help for my website

  32. roastgoat

    Hi Remi, you have provided a great tutorial and robust overview of the process required to add custom fields to WooCommerce product variations.

    Like a few others here, I am experiencing the Notice: Undefined Index call stack for the woocommerce_wp_text_input and woocommerce_wp_textarea_input arrays, etc. Specifically, the ‘value’ key $variation_data[].

    The call stack states that in line 27 of your example, 'value' => $variation_data['_text_field'][0] the ‘_text_field’ is an undefined index.

    I know the ‘Notice’ errors are not fatal, but as I am in development and have WP_DEBUG set to ‘true’, I prefer to grab these errors as they arise and fix them.

    I know how to fix undefined index in $_POST data but am unsure how to fix this upon field creation. If you or anyone else here could point me in the right direction, it would be great.

  33. Sorentk

    Hi.
    Thanks for the tutorial. I have added my Custom Field on each variation, and what I would like to do, is add a specific “product description” to each product variation.
    In other words; insert my ‘custom field text box’ into the ‘short product description’ location on the website – so whenever i change the ‘shade’ a specific description to that shade shows:
    Like shown here

    Is there a function to do this?

    Thanks in advance.

  34. […] a note that this tutorial does not cover adding custom fields to variable product, that process is covered in this tutorial by my fellow team member at WooThemes, Remi […]

  35. […] article is a guide on adding custom fields and product variation level while this articles shows you how to have a more dynamic display of custom fields in the front […]

  36. […] working with Woocommerce and following this great article, have added a few custom field within the product variations. I am able to view the custom fields […]

  37. Aaron

    For the life of me I can not get the data to display…

    woocommerce_wp_text_input(
    array(
    'id' => '_amazon[ + loop + ]',
    'label' => __( 'Amazon URL', 'woocommerce' ),
    'placeholder' => 'http://',
    'desc_tip' => 'true',
    'description' => __( 'Amaon URL here', 'woocommerce' ),
    'value' => $variation_data['_text_field'][0]
    )
    );

    I have tried this:

    $_amazon = get_post_meta( $var_id, '_amazon', true ); echo $_amazon;

    I dont see how this will change also if you select a different veriation??

    A

    1. Willem-Siebe

      Tried the same, did you worked it out?

  38. PatrickWolf

    Hello Remi,

    I’m using this method in combination with the store exporter plugin, but somehow the information is not beeing collected. I used the orginal names of your script just to make sure i did’nt make any errors.

    But when i add ‘_number_field’ in the custom products fields it is not showing any data in the export. Any idea?

    1. oococc

      it is most probably because on the line 253 should be:

      if ( isset( $_number_field[$i] ) ) {

      instead of:

      if ( isset( $_text_field[$i] ) ) {

  39. oococc

    thanks for the article!

  40. gabrielle

    Hi,is it possible to change dropdown list into text input?
    My project drives me crazy, i added so many variation, and now i need change everything into input text ;/
    Would you know any source/links/scripts how to do that?
    I’m searching a way to change the price for product in real-time like that:
    if width = 40cm to 80cm AND height = 80cm to 100cm THEN price =myValue
    Best regards, gabrielle

  41. somnath

    Hi,
    I was wondering if you can help me on some variation problem in Woocommerce. I am building a site for cusotm courier service using woocommerce, and I am preparing variation of my product, I saw there is a parent field in attributes term addition page.

    I want to create an attribute, which will have a term like zone, and under that zone I want to have name of some cities whose parent would be zone.
    Now in product variation I want to select the parent term create a variation of that parent Item so that all the children of that term can use the variation product of their parent, I don’t want to create variation for each child term.
    So is it possible to do this by writing some plugin for woo commerce to achieve this scenario ?
    Please help if you think its possible.

  42. gabrielle

    Hi, i have variable product where price depend on width and height,for example:
    if iwidth >=40cm || =60cm || <=80cm then price=myValue, else if width (…)
    How can i add for each variation 2 number input fields for width and height and min max values to them ?
    I try measurement price calculator, acf,products add-on, gravity forms(…), but i need something else, coz my product a,d,g have different price cathegory than product b,g,k
    Could you,plese give me advice/links/resources how to achieve that?
    Best regards, Gabirelle

  43. guilhermemarconi

    Hi, Remi!

    Great post!

    I am testing something for (maybe) use in the future and this could work really well! But I need some help…

    1st. I can’t display the value of the input. I set the get_post_meta() correctly but it still doesn’t working. I set the $key argument correctly (I think) but it returns nothing.
    Here’s the call: get_post_meta( get_the_ID(), '_color_field', true );
    I set the same $key argument that is set in the update_post_meta at save_variable_fields function and it’s ok on the variations form, saving its value normally.

    2nd. There was a possibility of create a color input rather than text, hidden, number, etc? It’ll be easy for the people who doesn’t know how to get HEX color values to set in a text input.

    Sorry for my english and thanks for the help!

    1. Searching a little more, I found out how to create the color input, with the type argument on woocommerce_wp_text_input(); function.

      But I still can’t get the field value with get_post_meta(); function. It returns an empty string. :(

      Sorry for bothering you, but it’ll help me a lot!

      1. Kahil

        Has anyone been able to get the values to display on the front end? No matter the combo, I simply can’t get it to display anything…it’s just empty on the front end.

        1. kristofferp

          I have the same problem; I´m trying
          $var = get_post_meta( get_the_ID(), ‘_text_field’, true ); Adding for example the variations ID directly (for example “501” instead of “get_the_ID()” works, but I can´t get the variations id dynamic or anyhow display it on the cart-page. Please help me!

          1. kristofferp

            10 hours later I found a solution:
            get_post_meta( $_product->variation_id, ‘_text_field’, true );
            Thank you for post Remi!

  44. Hey Remi,

    very great post. I tried this and the other tutorial for simple products.
    But when i use both (in the Plugin Toolbox for the snippets for the functions.php) there will be errors by using the fileds. I will be very thankfull, when you could helb me with an idea…:

    How can i implement a rule that only the part of the variable product will only be loaded when it is a variable one and the part for simple products will be loaded when it is really a simple product.

  45. Kahil

    If I simply copy/paste this code into my functions.php file, it doesn’t work. I get “unexpected” errors. I’ve never had issues with doing similar tasks before

    1. Kahil

      Ok, with some careful edits to previous items in my functions.php file, I have it working….but the issue is just one thing….displaying it on the front end.

      The get post meta function simply isn’t working. All I ever get is an empty return. It looks like others are having this issue as well. Any solution?

  46. haogar

    For some reason, mine is not saving, not sure why, I just copied and pasted the code into ‘functions.php’, the fields show in the variations tab, but when I update all the data disappears

  47. michelle

    Hey Remi,

    This is great, and exactly what I need. However, using the code exactly as is, there’s no saving happening of any of the fields. They show up on variable products as expected, but none of them save.

    I disabled all non-woocommerce plugins, and still no dice. Any chance this is related to WC 2.3?

    1. I need to check if it’s WC 2.3 related, and if needed i’ll update the code ;-)

      1. lemonthirst

        Hi Remi,
        i am using the WC 2.3 as michelle mentioned above i think it’s related to the latest update.
        In my case the fields are saved, everything works ok on the frontend, but when a edit/update is made to the product the custom values get deleted.

        Thanks!

        1. Ok, I need to try the code with the latest WC version

          1. squid

            Do you happen to know if there’s a fix or workaround for this? I’ve been trying desperately to get this to work on WC 2.4.6, but the values won’t save. :-/

      2. gkeiner

        Hi Remi,
        Since “upgrading” to WC 2.3, this broke whereas it was previously working.
        I see the fields in the variations section of the product admin, but it doesn’t retrieve the data any longer. If you have any insight, I’d really appreciate it!

  48. It is saving, because the content of my custom fields does show up on the front end exactly the way I want it to. But, it is not retrieving the data out of the database the next time you edit the product, and if you save, the fields are empty in the form and will be saved empty, overwriting the data in the database.

    I don’t know how to fix it, but if you’re careful about updating your products, it does work.

  49. nathangeorge

    Still investigating a bunch of stuff this latest WooCommerce update has broken, but custom fields for variations are now required to have ‘attribute_’ prefix the name i think.

    I found this validation in /wp-content/plugins/woocommerce/includes/admin/meta-boxes/class-wc-meta-box-product-data.php on line 782.

    foreach ( $variation_meta as $key => $value ) {
    if ( false !== strpos( $key, ‘attribute_’ ) ) {
    $variation_data[ $key ] = $value;
    }
    }

    The variable $variation_meta is grabbed via:

    $variation_meta = get_post_meta( $variation_id );

    In previous versions of WooCommerce meta was just added to variation data like:

    $variation_data = get_post_meta( $variation_id );

    Very frustrating!!!!

  50. Another thing if you actually using these values somewhere. If you are iterating through cart contents with something like $cart_object->cart_contents, there used to be an array for variations called $value[‘data’]->product_custom_fields.

    This longer exists.

    You can just get_post_meta on the variation_id. I originally had:

    $_carton_price = $value[‘data’]->product_custom_fields[‘_carton_price’][0];

    Which i replaced with:

    $_carton_price = get_post_meta( $value[‘product_id’], ‘_carton_price’, true );

    Hope this helps someone.

    1. Thanks for the heads-up!

  51. Hi Remi,

    same issues as described by BranceG on my site since the wc update.

    Since I really like your piece of code, it would be really great if you could update it to the new version! ;-)

    Thanks!
    Seb

  52. mbagri

    Hi Remi,

    thank you for the great plugin.

    Is there any solution to the problem with not displaying fields.

    It seems that “$variation_data[‘_text_field’][0]” doesn’t work. If you change this value with a fix value, it is displayed.

    I tried following customization which works well when I set the $variation_id manually . But I don’t know how to get the variation_id programmatically. Do you have any idea?

    function variable_fields( $loop, $variation_data ) {
    $variation_id = xxx;
    $variation_data = get_post_meta($variation_id);

    ?>

    ‘_text_field[‘.$loop.’]’,
    ‘label’ => __( ‘My Text Field’, ‘woocommerce’ ),
    ‘placeholder’ => ‘http://’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Enter the custom value here.’, ‘woocommerce’ ),
    ‘value’ => $variation_data[‘_text_field’][0]
    )
    );
    ?>

  53. […] this post I’ve added custom fields to the variations. One being the amazon […]

  54. edgy63

    Hi,
    I have the same problem with the non saving data with woocommerce 2.3+.
    I have read that you were trying to fix it.

    did you managed?
    Thankyou

    1. sorry i haven’t worked on the update yet ;-)

      1. champton

        The data saves. I see it in the DB post meta, but it does not display when you go back to the variation and try to edit form the product admin page.

      2. cannect

        Hi @Remi,

        Thanks for your great code, I got it working here in my dev environment. Seems like WooCommerce 2.3 dropped the support for using $variation_data, or they are not willingly to fix the bug, see: https://github.com/woothemes/woocommerce/issues/7675

        See my working gist here: https://gist.github.com/cannect/09fdbdd569020e2a0ff1
        Disclaimer: just edited your code from the top off my head, so please compare the differences in the code and you are good to go.

        Maybe you should edit your story above? ;-)

        1. whoaloic

          It seems that the code has an error with value parameters in woocommerce_wp_text_input functions (i.e ‘value’ => get_post_meta($variation->ID, ‘_text_field’], true))

    2. blackaholic

      Hello,

      I got same issues too. The fields are showing, but when I add the value, the value is not saved.

  55. Leanne

    Great article, thanks!

    I am having the same issue with the data in the fields not saving with the current version of WordPress 4.1.1 and WooCommerce 2.3.5. Hoping you can update soon with a solution for saving the data in the fields.

    Otherwise I guess it’s back to the drawing board :)

  56. williambijker

    When will this compatible with 2.3+?

    Looking forward to use this!

  57. […] was thinking of using this solution http://www.remicorson.com/woocommerce-custom-fields-for-variations/ but can’t yet figure out how to make a price addition in the product and category […]

  58. Achim

    Dear Remi.
    Thanks a lot for this great description, helped me loads!

    Maybe you should consider updating this post as in Woocommerce 2.3.5 a few things seem to have changed.
    I’m a total newbie to Woocommerce so please correct me if I’m wrong, but however I got your script running with tiny adjustments:

    – the action woocommerce_product_after_variable_attributes_js seems no longer in use (it’s never called and i couldn’t find a hook called like this in wc)
    – tables seem no longer be used for the form layout
    – there’s a typo in #253, it should say “$_number_field”, I guess
    – the fields are saved to wp_postmeta but are not displayed in the admin’s variation form, this is due to the loop in class-wc-meta-box-product-data.php#750 – it seems to be there to remove unknown fields.

    My Solution:
    I hacked this by simply adding my custom-field-keys to $variation_fields (and put their values to the 0-index of an array) but there should be a clean way to do this.
    Not sure, it looks like you’re a contributor to Woocommerce?
    How about setting up a new hook such as woocommerce_product_variation_register_field that would be run through initially and that could modifiy the field list in this file?

    I hope this is valid input please bear in mind I just work with WC since a couple days and have no deeper insights.
    Again thanks a lot for figuring this out for us!

    Best regard
    Achim

  59. patgilmour

    To get the fields displaying again, I’ve done the following. (Disclaimer: I have no idea if it the “correct” way, but it works.)

    For the hook, add back the ‘3’. So change it from:
    add_action( ‘woocommerce_product_after_variable_attributes’, ‘variable_fields’, 10, 2 );

    to:
    add_action( ‘woocommerce_product_after_variable_attributes’, ‘variable_fields’, 10, 3 );

    Then in the function add back $variation, so:
    function variable_fields( $loop, $variation_data, $variation ) {

    Once you have $variation, get the ID (inside the function):
    $my_variation_id = $variation->ID;

    Once you have the ID, you can call the post meta directly to get it to display on your admin page, some thing like this:
    ‘value’ => get_post_meta($my_variation_id, ‘_my_field_name’, true );

    I *think* the reason the old code no longer works is because when WooCommerce gets the post meta from the database, it now only gets the default WooCommerce fields, not the extra ones you have added.

    You can see this in action by doing a print_r inside the function:
    print_r( $variation_data );

    It won’t contain your meta fields any more.

  60. Olivier

    Hello,

    Thank you for this post, and the other ones.

    Like others I have an issue to retrieve the value of a custom meta.
    In WooCommerce (2.3.5 for me) the variation fields are hardcoded. You can see it in class-wc-meta-box-product-data.php line 755. So we can’t use the $variation_data array directly.

    A good thing is that the hook woocommerce_product_after_variable_attributes() has a 3rd argument which is the current variation object.

    So we just have to modify the code a bit:

    add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 );

    function variable_fields( $loop, $variation_data, $variation ) {
    woocommerce_wp_text_input( array(

    'value' => get_post_meta($variation->ID, '_text_field', true),

    ) );

    I hope it will help

  61. barakd

    This is my temp fix for 2.3, untill woocommerce will solve this issue.
    Go to the file:
    wp-content\plugins\woocommerce\includes\admin\meta-boxes\class-wc-meta-box-product-data.php
    on line: 784
    foreach ( $variation_meta as $key => $value ) {
    if ( false !== strpos( $key, ‘attribute_’ ) ) {
    $variation_data[ $key ] = $value;
    }

    change the if condition to:
    if ( !array_key_exists($key,$variation_fields) )
    this worked for me, for the meanwhile.

  62. champton

    Great article. Just what I needed. I am using the select box but when I update the product, it does not show my selected choice. I show the correct choice in the database. Is there a key=> value that I have to set to make the core selected() function work?

  63. diego89

    For me the fix with adding “attribute_” to the fields the code worked.
    Thanks

    1. haogar

      Hi, sorry, could you elaborate on that? I’m not really experienced with php, where did you add ‘attribute_’ I would love to check if it works for me

  64. shork

    Hi,

    great tutorial!!! how can add a image field?

    Thanks

  65. jeremyvotaw

    Have you thought about, or could this be used as a price modifier? This variant is +10, +18, -5, etc… for example?

  66. ccls

    Hi,

    Can’t find a better tutorial online for variation custom fields than this, so thanks a lot.

    I too had the same problem with filling the custom fields with the correct value and followed the instructions above and everything seems to be working which is great.

    However, I’m just wondering if all of the hooks you use are still correct or if they’ve been deprecated? I can’t find

    woocommerce_product_after_variable_attributes
    woocommerce_product_after_variable_attributes_js

    in the api documentation and (as pointed out) the woocommerce_variation_options hook works fine (I even removed the hook for the JS and everything works as normal)

    Thanks in advance,

    Chris

  67. ahsan

    Dear Remi.

    i am using the above code, but it can’ work properly. basically i am trying to show only number field, it shows properly in variation, but unfortunately the value of that field is not updated when i click on update post.

    any solution.

    here is my code.
    //Display Fields
    add_action( ‘woocommerce_product_after_variable_attributes’, ‘variable_fields’, 10, 2 );
    //JS to add fields for new variations
    add_action( ‘woocommerce_product_after_variable_attributes_js’, ‘variable_fields_js’ );
    //Save variation fields
    add_action( ‘woocommerce_process_product_meta_variable’, ‘save_variable_fields’, 10, 1 );

    /**
    * Create new fields for variations
    *
    */
    function variable_fields( $loop, $variation_data ) {
    ?>

    ‘_number_field[‘.$loop.’]’,
    ‘label’ => __( ‘Product variation Number’, ‘woocommerce’ ),
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Enter Product variation Number.’, ‘woocommerce’ ),
    ‘value’ => $variation_data[‘_number_field’][0],
    ‘custom_attributes’ => array(
    ‘step’ => ‘any’,
    ‘min’ => ‘0’
    )
    )
    );
    ?>

    ‘_hidden_field[‘.$loop.’]’,
    ‘value’ => ‘hidden_value’
    )
    );
    ?>

    ‘_number_field[ + loop + ]’,
    ‘label’ => __( ‘Product variation Number’, ‘woocommerce’ ),
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Enter Product variation Number.’, ‘woocommerce’ ),
    ‘value’ => $variation_data[‘_number_field’][0],
    ‘custom_attributes’ => array(
    ‘step’ => ‘any’,
    ‘min’ => ‘0’
    )
    )
    );
    ?>

    ‘_hidden_field[ + loop + ]’,
    ‘value’ => ‘hidden_value’
    )
    );
    ?>

    <?php
    }

    /**
    * Save new fields for variations
    *
    */
    function save_variable_fields( $post_id ) {
    if (isset( $_POST['variable_sku'] ) ) :

    $variable_sku = $_POST['variable_sku'];
    $variable_post_id = $_POST['variable_post_id'];

    // Number Field
    $_number_field = $_POST['_number_field'];
    for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    $variation_id = (int) $variable_post_id[$i];
    if ( isset( $_text_field[$i] ) ) {
    update_post_meta( $variation_id, '_number_field', stripslashes( $_number_field[$i] ) );
    }
    endfor;

    // Hidden field
    $_hidden_field = $_POST['_hidden_field'];
    for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    $variation_id = (int) $variable_post_id[$i];
    if ( isset( $_hidden_field[$i] ) ) {
    update_post_meta( $variation_id, '_hidden_field', stripslashes( $_hidden_field[$i] ) );
    }
    endfor;

    endif;
    }

  68. shir.gans

    Hello,
    If someone is looking for a fix. Here is a code (shortened) that works.

    ‘_purchase_price[‘.$loop.’]’,
    ‘label’ => __( ‘Purchase Price’, ‘woocommerce’ ),
    ‘value’ => get_post_meta($variation->ID, ‘_purchase_price’, true),
    ‘custom_attributes’ => array(
    ‘step’ => ‘any’,
    ‘min’ => ‘0’
    )
    )
    );
    ?>

    ‘_purchase_price[ + loop + ]’,
    ‘label’ => __( ‘My Number Field’, ‘woocommerce’ ),
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Enter the custom number here.’, ‘woocommerce’ ),
    ‘value’ => $variation_data[‘_purchase_price’][0],
    ‘custom_attributes’ => array(
    ‘step’ => ‘any’,
    ‘min’ => ‘0’
    )
    )
    );
    ?>

    <?php
    }

    /**
    * Save new fields for variations
    *
    */
    function mystore_purchase_price_save_variable_fields( $post_id, $post ) {
    global $variation_data;

    if (isset( $_POST['variable_sku'] ) ) :

    $variable_sku = $_POST['variable_sku'];
    $variable_post_id = $_POST['variable_post_id'];

    // Number Field
    $_purchase_price = $_POST['_purchase_price'];
    for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
    $variation_id = (int) $variable_post_id[$i];
    if ( isset( $_purchase_price[$i] ) ) {
    update_post_meta( $variation_id, '_purchase_price',$_purchase_price[$i] );
    }
    endfor;

    endif;
    }

  69. skumyol

    Hi,
    Sorry if it’s irrelevant or answered question. I want to put 3 checkboxes to product page so customers could add some features to product and checkboxes should dynamically manipulate the price. And i want to see checked fields at orders . Do you have any suggestions ?

  70. sprclldr

    For those having issues with the values displaying properly in the admin, I had to prepend “_attribute” to the field names, as recommended by barackd and deigo89.

    An example of this is “_text_field” becomes “_attribute_text_field” or “_checkbox” becomes “_attribute_checkbox”. Replace those in your code and everything will work.

    Then, of course, output to the front end inside your will be something like:

    $var_id = $cart_item[‘variation_id’];
    echo get_post_meta( $var_id, ‘_attribute_text_field’, true );

    1. i updated the code, adding “attribute” isn’t required.

  71. Kamkya

    Hi Remi

    Are you able to tell me whether these additional fields will be responsive to a product or site search? Thank you

  72. whoaloic

    Thank you for updated the code Remi.
    I’m still looking for a way to show/hide the custom field data per the respective product variation selected by the user.

    Did anybody suceed in doing that?
    Cheers?

    1. what do you want to do exactly?

  73. whoaloic

    I’d like to show custom field variation value on the single product page.
    By example:
    I have a variable product with “size” attribute.
    The variations of the variable product are “Small”, “Medium”, “Large”.
    Each variation has a different “variable_text_field” value.
    When a user select a variation, I would like to show the respective value of the “variable_text_field” field.
    I read this: http://blueskysessions.com/2014/03/31/woocommerce-display-dynamic-content-per-the-selected-product-variation/
    or this https://gist.github.com/kloon/4228021#comment-1177265
    but that did not help me :(

    1. whoaloic

      Hi Remi,
      I’m just following up my previous message because I’d like to know if you know a code snippet to display custom fields values for variations in the frontend.
      Cheers.

      1. whoaloic

        Here’s a solution to display custom field value for variation:
        In the [theme]/woocommerce/single-product/add-to-cart/variable.php, below .
        ID, ‘variable_custom_field’, true);

        $custom_data[$variation_id] = array(
        “custom_field_value” => $variable_custom_field
        );
        endforeach;
        ?>

        Custom field :

        jQuery(function($) {
        var variation_custom_fields = ,
        variations_data = JSON.parse( $(‘form.variations_form’).first().attr( ‘data-product_variations’ ) ),
        $selected_variation_custom_field = $(‘.selected-variation-custom-field’); // see DIV above

        $(‘table.variations’).on(‘change’, ‘select’, function() {
        var $select = $(this),
        attribute_name = $select.attr(‘name’),
        selected_value = $select.val(),
        custom_field_value = “”;

        // Loop over the variations_data until we find a matching attribute value
        // We then use the variation_id to get the value from variation_custom_fields
        $.each(variations_data, function() {
        if( this.attributes[ attribute_name ] && this.attributes[ attribute_name ] === selected_value ) {
        custom_field_value = variation_custom_fields[ this.variation_id ].custom_field_value;
        return false; // break
        }
        });

        // doing this outside the loop above ensures that the DIV gets emptied out when it should
        $selected_variation_custom_field.text( custom_field_value );
        });
        });

        Some people could test it and give feedback?

        1. whoaloic


          ID, 'variable_custom_field', true);

          $custom_data[$variation_id] = array(
          "custom_field_value" => $variable_custom_field
          );
          endforeach;
          ?>

          Custom field:

          jQuery(function($) {
          var variation_custom_fields = ,
          variations_data = JSON.parse( $('form.variations_form').first().attr( 'data-product_variations' ) ),
          $selected_variation_custom_field = $('.selected-variation-custom-field'); // see DIV above

          $('table.variations').on('change', 'select', function() {
          var $select = $(this),
          attribute_name = $select.attr('name'),
          selected_value = $select.val(),
          custom_field_value = "";

          // Loop over the variations_data until we find a matching attribute value
          // We then use the variation_id to get the value from variation_custom_fields
          $.each(variations_data, function() {
          if( this.attributes[ attribute_name ] && this.attributes[ attribute_name ] === selected_value ) {
          custom_field_value = variation_custom_fields[ this.variation_id ].custom_field_value;
          return false; // break
          }
          });

          // doing this outside the loop above ensures that the DIV gets emptied out when it should
          $selected_variation_custom_field.text( custom_field_value );
          });
          });

          1. whoaloic

            I’m sorry for the duplicate message:
            Please see a solution here:
            https://wordpress.org/support/topic/display-custom-field-values-for-product-variations?replies=2#post-7083747

            What do you think about this?

  74. mskeet

    Hey Remi

    Cheers for this post – been most helpful with an issue with a field I needed to add to a site I’m working on.

    Just thought I’d mention though there’s an issue at line 253 of your code sample. You are referencing the text_field variable in the number_field save example so that code won’t save the values entered in the variations screen.

    Had me scratching my head for a wee while!

    1. Willem-Siebe

      Thanks! It’s strange though, because when I copy paste the COMPLETE code, it is saved, even with this typo. However, when I cut the code, only leaving the number field as custom field, it’s not working anymore. Changing it to number_field works in that case, but still strange why it’s working in the COMPLETE code.

  75. haogar

    Hi, I’m having trouble retrieving the data, the new code saves, but I have seriously no idea where to post the data, I have tried in many template files, but so far I haven’t had success

  76. razer1

    Hi Remi,

    I have got the code to save with a custom field – Trying to add a RRP price for all products ( Simple & Variables)

    I cannot get this to show in the frontend system of the site..

    Tried various combinations of the get_meta tag.

    Any help from anyone?

    This is the full code in the functions file I have atm. Some suggestions would be great to what to use to get the field to show above the price.

    ‘rrp_variation[‘.$loop.’]’,
    ‘label’ => __( ‘RRP Price’, ‘woocommerce’ ),
    ‘placeholder’ => ‘RRP: £’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘RRP Price for product’, ‘woocommerce’ ),
    ‘value’ => get_post_meta( $variation->ID, ‘rrp_variation’, true )
    )
    );
    ?>

    ‘rrp_variation[ + loop + ]’,
    ‘label’ => __( ‘RRP Price’, ‘woocommerce’ ),
    ‘placeholder’ => ‘RRP:£’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘RRP Price for Product’, ‘woocommerce’ ),
    ‘value’ => ”
    )
    );
    ?>

    <?php
    }

    /**
    * Save new fields for variations
    *
    */
    function save_variable_fields( $post_id ) {
    if (isset( $_POST['variable_sku'] ) ) :

    $variable_sku = $_POST['variable_sku'];
    $variable_post_id = $_POST['variable_post_id'];

    // Text Field
    $rrp_variation = $_POST['rrp_variation'];
    for ( $i = 0; $i

  77. tararotten

    Hiya,

    I’m trying to add variation checkboxes to each product so the user can select additional product options, ie tick a,b and c and include this on the order form. However I would like images to be associated with each checkbox option, is this possible?

  78. juanpablo

    thanks for the post, when i save the data is saved in the database but when i reload the page the field doesnt show the value.

    1. juanpablo

      Iv’e found the solution in the documentation, thanks, now i have a question how execute js beforeedit product

  79. alexicon

    The save_variable_fields() function seems to break after WC 2.4+ upgrade. Guess it has to do with the way WooCommerce now uses ajax for saving and retrieving data. Is there a fix for this?

    1. alexicon

      Managed to get things working again with WC 2.4+ by hooking the “save_variable_fields()” function to another action. Instead of “woocommerce_process_product_meta_variable” I use “woocommerce_save_product_variation”. Not sure if this is a fool-proof fix, but seems to work just fine as far as I can tell…

      Not sure if priority needs to be set, but this is what I’ve got (on line 8 in the code example above):

      add_action( ‘woocommerce_process_product_meta_variable’, ‘save_variable_fields’, 10, 1 );

      1. alexicon

        Oops, to fast with the copy/paste there. Pasted the old code by mistake.. :P

        THIS is what I’ve got (on line 8 in the code example above):

        add_action( ‘woocommerce_save_product_variation’, ‘save_variable_fields’, 10, 1 );

  80. johncarter

    Hey Remi,

    Thanks for the example code.

    Depsite WooCommerce saying the new WooCommerce 2.4 variations will be backward compatible, it doesn’t seem this is the case. I can see the field but it isn’t saving.

    Is there any chance you will be updating this for 2.4?

    All the best!

  81. johncarter

    @alexicon

    It seems you were struggling with the same thing as me. I just took a look at the comments on the Development blog: https://woocommerce.wordpress.com/2015/07/13/improving-the-variations-interface-in-2-4/

    In the comments, Danny Hearnah has posted:

    For anyone using the action woocommerce_process_product_meta_variable – this no longer works and so I had to change to woocommerce_save_product_variation

  82. alberto

    For those who still have problems to show custom variations, here I found a solution that worked for me: https://www.openstream.ch/developer-blog/woocommerce-grundpreisangabe/

    I used the code of Remi (thank you for your great job!) to write the data in the db, and the code of the other link to output the result.

    Cheers

  83. rizalhasbianto

    Hello all,

    I have same issue ” can’t save the custom field”, so I try to play with this code and make small change on the code and boom it working for me.

    here is the code :
    //Save variation fields
    add_action( ‘woocommerce_save_product_variation’, ‘save_variable_fields’, 10, 2);

    on save_variable_fields function :
    // Select
    $_select = $_POST[‘_select’];
    for ( $i = 0; $i <= 100; $i++ ) :
    $variation_id = absint( $variable_post_id[ $i ] );
    if ( isset( $_select[$i] ) ) {
    update_post_meta( $variation_id, '_select', stripslashes( $_select[$i] ) );
    }
    endfor;

    Hope this can help!

  84. hknerdr

    Hi
    I still can’t save my text field. I enter an url when i click save settings, it just disappears.

    I use WP 4.3, woo commerce 2.4.6

    Can you please fix it?

    Thank you
    Regards

    1. rizalhasbianto

      Hello,

      I am not sure about the text field, but you can change the following code :
      // Text Field
      $_text_field = $_POST[‘_text_field’];
      for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
      $variation_id = (int) $variable_post_id[$i];
      if ( isset( $_text_field[$i] ) ) {
      update_post_meta( $variation_id, '_text_field', stripslashes( $_text_field[$i] ) );
      }
      endfor;
      to
      // Text Field
      $_text_field = $_POST['_text_field'];
      for ( $i = 0; $i <= 100; $i++ ) :
      $variation_id = absint( $variable_post_id[ $i ] );
      if ( isset( $_text_field[$i] ) ) {
      update_post_meta( $variation_id, '_text_field', stripslashes( $_text_field[$i] ) );
      }
      endfor;
      Thanks, Hope this can help!

    2. mboden

      I had the same issue. Found this link, which worked for me.

      https://gist.github.com/gbyat/c1bcc9f47ef9e661fc6f

      Hope it helps.

    3. gore.m

      Same here :-(

  85. JeremyBrookes

    Hi Remi,
    Thanks for these tutorials.
    I was wondering if it’s possible to add a custom field to a variable product, but in the general (or a custom) tab? Something like a cross between this approach and the previous one (Mastering WooCommerce Products Custom Fields). The earlier approach shows up fine in a simple product but doesn’t show for a variable product. I don’t want to have a custom field per variation (or do I have to?), but just a custom field for the parent product (if that makes sense).

    Many thanks

  86. rishabh58

    Hello Remi,

    Please help me.

    When I am trying to copy paste above code in my function.php file its get crashed. I cant figure it out. Please help me.

  87. hardik

    Hello,
    I am using WooCommerce plugin for my online marketplace site.
    My site is multi-vendor marketplace for digital products.

    I have add one custom field on product submission in back-end, and it is work fine in back-end product submission.
    But I want to add same custom field in front-end product submission form.
    Here is the code I have added in themes functions.php file to display custom field in back-end.

    // Display Fields
    add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

    function woo_add_custom_general_fields() {

    global $woocommerce, $post;
    // Text Field
    $playstore_url_text_field = woocommerce_wp_text_input(
    array(
    'id' => 'playstore_url',
    'label' => __( 'App Play store URL', 'woocommerce' ),
    'placeholder' => 'http://',
    'desc_tip' => 'true',
    'description' => __( 'App Google Play store URL', 'woocommerce' )
    )
    );
    }

    // Save Fields
    add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
    function woo_add_custom_general_fields_save( $post_id ){

    // Text Field
    $playstore_url_text_field = $_POST['playstore_url'];
    if( !empty( $playstore_url_text_field ) ) {
    update_post_meta( $post_id, 'playstore_url', esc_attr( $playstore_url_text_field ) );
    } else {
    update_post_meta( $post_id, 'playstore_url', '' );
    }
    }

    Using above code, I have add one custom text field in back-end and it is work perfect with add, update and delete functionality.

    How can I add same custom text field in front-end?
    Here is my code for front-end text field.

    <input class="" type="text" name="playstore_url" value="" />

    One thing, If I will add this custom field value from front-end then value should be added to that custom field in back-end and vice versa.

    Thanks in advance.

    https://wordpress.org/plugins/woocommerce/

  88. wpnimitz

    Any chance I could retrieve the variation being selected?

  89. menardmam

    Hi, first thanks for this great code, it work… but i have found a major BUG…. you can check the _checkbox, safe it, and it’s fine. But if you change your mind, and unchecked it… save it, it’s still check… always and forever… can you please review the code and tell me what to change to make it work on and off…. for now deleting the variation COMPLETELY and re-creating this variation clear the checkbox… but it’s a pain in the a$$ thanks in advance

    1. yeah, it needs to be updated, i’ll do it asap, sorry about that ;-)

      1. menardmam

        Thanks, we all have busy week, client to please and thing to do. Your code was integrated into my site, and i myst have it up and running in the next two week. Do you think it’s possible for you to have a look and a fix in that timeframe ? i have try to debug the code, but it’s way beyond my knowledge

        1. It’s been updated ;-)

  90. gaurang

    Hi Remi,
    Can I move the new text field under SKU field on product variations ?

    1. I guess you can, but it would require a bit of extra coding which goes a bit beyond the scope of that post.

  91. whoaloic

    Hello,
    Thank you Remi for updating the snippet for WC 2.4+.
    I experience a strange issue. I can’t update the value of a text field when the new value is 0 or empty.
    Any idea to help me please?
    Regards.

  92. Igor

    Hello,

    Thanks for the great article.

    However, I am having difficulties with saving variation data fields. Firstly, I modified the saving function (it did not work in the way it is in the article):

    function save_variation_settings_fields( $variation_id ) { // we have variation id as an argument for woocommerce_save_product_variation, not post id

    $uk_price = $_POST[‘_uk_price_var’][ $variation_id ];

    if( ! empty( $uk_price ) ) {
    update_post_meta( $post_id, “_uk_price_var[$variation_id]”, esc_attr( $uk_price ) ); // include variation id to the field name
    }
    }

    And this would work if we knew the $post_id. The woocommerce_save_product_variation fires too early to get it from $post, we cannot get it through $_POST[‘post’]. Any ideas?

    1. Igor

      I should have taken a look into the $_POST we have. Managed to get the post id from $_POST[‘product_id’].

      Now the function works fine and looks like this:

      function save_variation_settings_fields( $variation_id ) {
      $uk_price = $_POST[‘_uk_price_var’][ $variation_id ];
      $product_id = $_POST[‘product_id’];

      if( ! empty( $uk_price ) ) {
      update_post_meta( $product_id, “_uk_price_var[$variation_id]”, esc_attr( $uk_price ) );
      }
      }

      1. Igor Skoldin

        Another thing, I would change this !epmty() checking everywhere to isset() because otherwise we are not able to remove the value of the field.

  93. ReddaJoppe

    If I put that code at the end of my theme’s functions.php, the entire website goes blank. Am I doing something wrong? Should the code go someplace else? Should I do more than add the code?

    1. There’s probably an unclosed PHP tag, what is the error message that you get when enabling the debug mode?

  94. ReddaJoppe

    There’s no debug.log file in my wp-content directory. Frontend just displays Server error 500.

  95. ReddaJoppe

    Well, removing the initial <?php tag did the trick…

    Now my challenge is to get the value I enter in the field to show in frontend in the Additional Information tab. I don't suppose there's a ready solution for this?

  96. mcdonagg

    I am wondering if it is possible to add tags to individual Variations? I would like to add a box to my variations that acts like the tag box at the product level, where you can select already created ones or create new ones. Ultimately I would like to be able to filter by these tags. I have setup my store to show all the variations on the shop page but would like to filter them down. But since they all share taxonomies with each other because they inherit them from their parent product there is no way to separate them. Do you know of any way to do this?

    1. mcdonagg

      Or categories, can categories be added to individual variations?

  97. nward85

    Great source. However I was curious if custom fields could generate information from current user profile fields, instead of having a user enter information overtime they purchase. For example, their favorite color.

  98. whoaloic

    SInce 2.5 WC version, there is a variable.php file.
    I think there is a easier way to display variation field in this file.
    Any help please?

    1. I updated the code ;-)

      1. whoaloic

        Wonderful!
        What if we need to display nothing if there is no value in the variation field?

        1. you can do a simple conditional statement ;-)

          1. whoaloic

            In the functions.php or in the variation.php?

          2. in variation.php

          3. whoaloic

            I try this in my variation.php file:

            My text field : {{{ data.variation.text_field }}}

            Without luck :(

          4. Bgill128

            I am having a really tough time with all of this. I can always get everything to show on the backend but NEVER get anything to show on frontend.

            The code that I am placing into functions.php is also causing an error on my site and is making white screen with error code in functions.php file =\

            I have tried the several methods from Remi and other places and even mixtures of all methods and cannot seem to figure this out. Has anybody gotten everything working and can post their ENTIRE guide to how to get items to show frontend?

            I think I am simply naming some of them incorrectly possibly or they are not knowing what to echo on the frontend.

            Any help would be appreciated and I am willing to pay to learn how to do this.

            Thank you all for your time.

        2. whoaloic

          Hello sorry to bother you again but I’m still stuck with the conditional statement.
          I try to show a text before variation text_field only if text_field is set.

          Kind regards.

  99. thetipico

    Now it works perfect !!!

    I would like to know how you found the hook “woocommerce_available_variation” on WooCommerce API documentation.

    For simple products, is there something like “woocommerce_product_after_variable_attributes” hook?

    Thank you!

  100. calexbrown

    So I successfully figured out how to display the information for a single product in the product attributes table, but I am not sure exactly how to get the data from the field in the table.

    Heres the code I re-wrote in the product-attributes.php folder. I used the ISBN and Barcode plugin as my main foundation…. I’m a designer, not a coder.
    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    Now, how would I get the variation field data to show up in the table? Make sense?

  101. calexbrown

    2 things:

    1. After hitting update, it hangs on post.php

    2. I successfully coded to display fields for a single product to show in product attributes table. I modified the ISBN and Barcode plugin. Is it possible to have the variation field data show in the product attributes table as well?

    Heres the code for adding fields… it’s set up the same with the save the fields, etc. This remained in the plugin file:
    // Text Field
    woocommerce_wp_text_input(
    array(
    ‘id’ => ‘GTIN-14’,
    ‘label’ => __( ‘GTIN-14’, ‘woocommerce’ ),
    ‘placeholder’ => ‘GTIN-14 here’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘GTIN-14.’, ‘woocommerce’ )

    Then I modified the code in product-attributes.php to display it in the table underneath the “Additional Information” tab:
    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    I tried the following code, but in the table value it displayed ” {{{ data.variation.text_field }}}”
    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    {{{ data.variation.text_field }}}

  102. calexbrown

    2 things:

    1. After hitting update, it hangs on post.php

    2. I successfully coded to display fields for a single product to show in product attributes table. I modified the ISBN and Barcode plugin.

    Is it possible to have the data from text field show in the product attributes table instead of just in the open?

    Heres the code for adding fields… it’s set up the same with the save the fields, etc. This remained in the plugin file:
    // Text Field
    woocommerce_wp_text_input(
    array(
    ‘id’ => ‘barcode’,
    ‘label’ => __( ‘Barcode’, ‘woocommerce’ ),
    ‘placeholder’ => ‘barcode here’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Product barcode.’, ‘woocommerce’ )
    )
    );

    Then I modified the code in product-attributes.php to display it in the table underneath the “Additional Information” tab:

    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    I tried the following code, but in the table value it displayed ” {{{ data.variation.text_field }}}”

    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    {{{ data.variation.text_field }}}

  103. calexbrown

    2 things:

    1. After hitting update, it hangs on post.php

    2. I successfully coded to display fields for a single product to show in product attributes table. I modified the ISBN and Barcode plugin.

    Is it possible to have the data from text field show in the product attributes table instead of just in the open?

    Heres the code for adding fields… it’s set up the same with the save the fields, etc. This remained in the plugin file:
    // Text Field
    woocommerce_wp_text_input(
    array(
    ‘id’ => ‘barcode’,
    ‘label’ => __( ‘Barcode’, ‘woocommerce’ ),
    ‘placeholder’ => ‘barcode here’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Product barcode.’, ‘woocommerce’ )
    )
    );

    Then I modified the code in product-attributes.php to display it in the table underneath the “Additional Information” tab:

    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    I tried the following code, but in the table value it displayed ” {{{ data.variation.text_field }}}”

    has_dimensions() ) : $has_row = true; ?>
    <tr class="”>

    {{{ data.variation.text_field }}}

  104. […] I have successfully been able to follow Remi’s tut on how to add custom fields for variations. […]

  105. […] I have successfully been able to follow Remi’s tut on how to add custom fields for variations. […]

  106. oscarabadfolgueira

    Hi, Remy.

    Great Tutorial!!

    I want to display this custom variation fields below the featured image.

    Do you know how can I do this?

    Thanks and regards!

    1. kbihler

      I also have it all working great but I am having a tough time moving output to a different area of my page. I have tried to put {{{ data.variation.text_field }}} in its own but i am not clear how to get it to process through the wp.template. The documentation on the codex is not clear (to me). Ultimately I want to display my custom fields in a product tab. Any help would be great.

      Thanks!

  107. jamieh05

    Hi Remi

    Just wondering of this would work for adding a supplier product cost price in woocommerce admin area for variable products so we can send an automated email to a supplier once an order has been placed for drop shipping. We use advanced notifications to send to the order to the supplier.

    Thanks

    Jamie

  108. teamjordy

    Hi all, since I struggled with this for a while, I figured I’d post what worked for me as of April 2nd, 2016.

    Woocommerce Version: 2.5.4
    Wordpress Version: 4.4.2

    In functions.php:

    //Display Fields
    add_action( ‘woocommerce_product_after_variable_attributes’, ‘variable_fields’, 10, 3 );
    //Save variation fields
    add_action( ‘woocommerce_save_product_variation’, ‘save_variable_fields’, 10, 2 );

    function variable_fields( $loop, $variation_data, $variation ) {
    global $post;
    if (!$post) $post = get_post($variation->ID);
    // Text Field
    $text_field = get_post_meta( $variation->ID, ‘_text_field’, true );
    woocommerce_wp_text_input(
    array(
    ‘id’ => ‘text_field[‘.$loop.’]’,
    ‘label’ => __( ‘My Label’, ‘woocommerce’ ),
    ‘placeholder’ => __( ‘My Placeholder’, ‘woocommerce’ ),
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘My Description’, ‘woocommerce’ ),
    ‘value’ => $text_field
    )
    );
    }

    function save_variable_fields( $variation_id, $i ) {
    // Text Field
    if ( isset( $_POST[‘text_field’][$i] ) ) {
    $text_field_value = stripslashes( $_POST[‘text_field’][$i] );
    update_post_meta( $variation_id, ‘_text_field’, $text_field_value );
    }
    }

    (add this in functions.php as well…)

    // Add New Variation Settings
    add_filter( ‘woocommerce_available_variation’, ‘load_variation_settings_fields’ );
    /**
    * Add custom fields for variations
    *
    */
    function load_variation_settings_fields( $variations ) {
    // duplicate the line for each field
    $variations[‘text_field’] = get_post_meta( $variations[ ‘variation_id’ ], ‘_text_field’, true );
    return $variations;
    }

    And since the documentation for syntax within was a bit scarce, here’s how I did a conditional statement to output my custom text field in variations.php:

    ${{{ data.variation.text_field }}}

    // etc…..

    Hope this helps!

  109. Astrit

    Hi there,
    I’ve stumbled upon a small issue using a CSV import to import custom fields. Despite that the importer is importing the key and value (and can be found in database) in the front-end as well as the admin panel the values are not assigned. What I mean is that if I manually echo the value in front end (like: echo get_post_meta( 15429, 'text_field', true ); ) the value is being correctly printed, but if I let the code handle the job it assumes as if there is no value added at all (i.e. acts as if the value was empty).

    Any hint on how to make double check that the variation ID has a populated value and update it accordingly?

  110. matt92

    Could some one update this, nothing working ?

  111. Bulent Gercek

    Hi Mr. Remi,

    Thanks for the great help with sharing your knowledge. I added some new fields to my admin area with your codes. But how can i take that form values after adding it and checking out? Because i need to use that information for a payment gateway plugin. Which array holding that form information? Thanks!

  112. filipvanreeth

    Hi,

    How can I make the input field required.
    I thought ‘custom_attributes’ => array( ‘required’ => ‘required’ ) was going to work, but it does not?

    Thanks for any tips.

  113. guestofhonor

    Hello,
    I have an issue that i hope you can help me with.
    I have an variation offer as follows:
    1- buy one only
    2- buy 2 and get discount.
    i have set the variation and it works for price, the issue is with the (buy 2 and get discount) that it won’t show size and color for the 2nd item !
    is there any way to do that ?
    Thanks in advance

  114. jackdowson1988

    Hello There,
    Help me out with below issue.
    I used the following code in functions.php but I am unable to see custom fields in my variation tab of a variable product. I am using version woocommerce 3.0.7.
    Please let me know if I missed something from my side.

    ‘_text_field[‘ . $variation->ID . ‘]’,
    ‘label’ => __( ‘My Text Field’, ‘woocommerce’ ),
    ‘placeholder’ => ‘http://’,
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Enter the custom value here.’, ‘woocommerce’ ),
    ‘value’ => get_post_meta( $variation->ID, ‘_text_field’, true )
    )
    );
    // Number Field
    woocommerce_wp_text_input(
    array(
    ‘id’ => ‘_number_field[‘ . $variation->ID . ‘]’,
    ‘label’ => __( ‘My Number Field’, ‘woocommerce’ ),
    ‘desc_tip’ => ‘true’,
    ‘description’ => __( ‘Enter the custom number here.’, ‘woocommerce’ ),
    ‘value’ => get_post_meta( $variation->ID, ‘_number_field’, true ),
    ‘custom_attributes’ => array(
    ‘step’ => ‘any’,
    ‘min’ => ‘0’
    )
    )
    );
    // Textarea
    woocommerce_wp_textarea_input(
    array(
    ‘id’ => ‘_textarea[‘ . $variation->ID . ‘]’,
    ‘label’ => __( ‘My Textarea’, ‘woocommerce’ ),
    ‘placeholder’ => ”,
    ‘description’ => __( ‘Enter the custom value here.’, ‘woocommerce’ ),
    ‘value’ => get_post_meta( $variation->ID, ‘_textarea’, true ),
    )
    );
    // Select
    woocommerce_wp_select(
    array(
    ‘id’ => ‘_select[‘ . $variation->ID . ‘]’,
    ‘label’ => __( ‘My Select Field’, ‘woocommerce’ ),
    ‘description’ => __( ‘Choose a value.’, ‘woocommerce’ ),
    ‘value’ => get_post_meta( $variation->ID, ‘_select’, true ),
    ‘options’ => array(
    ‘one’ => __( ‘Option 1’, ‘woocommerce’ ),
    ‘two’ => __( ‘Option 2’, ‘woocommerce’ ),
    ‘three’ => __( ‘Option 3’, ‘woocommerce’ )
    )
    )
    );
    // Checkbox
    woocommerce_wp_checkbox(
    array(
    ‘id’ => ‘_checkbox[‘ . $variation->ID . ‘]’,
    ‘label’ => __(‘My Checkbox Field’, ‘woocommerce’ ),
    ‘description’ => __( ‘Check me!’, ‘woocommerce’ ),
    ‘value’ => get_post_meta( $variation->ID, ‘_checkbox’, true ),
    )
    );
    // Hidden field
    woocommerce_wp_hidden_input(
    array(
    ‘id’ => ‘_hidden_field[‘ . $variation->ID . ‘]’,
    ‘value’ => ‘hidden_value’
    )
    );
    }
    /**
    * Save new fields for variations
    *
    */
    function save_variation_settings_fields( $post_id ) {
    // Text Field
    $text_field = $_POST[‘_text_field’][ $post_id ];
    if( ! empty( $text_field ) ) {
    update_post_meta( $post_id, ‘_text_field’, esc_attr( $text_field ) );
    }

    // Number Field
    $number_field = $_POST[‘_number_field’][ $post_id ];
    if( ! empty( $number_field ) ) {
    update_post_meta( $post_id, ‘_number_field’, esc_attr( $number_field ) );
    }
    // Textarea
    $textarea = $_POST[‘_textarea’][ $post_id ];
    if( ! empty( $textarea ) ) {
    update_post_meta( $post_id, ‘_textarea’, esc_attr( $textarea ) );
    }

    // Select
    $select = $_POST[‘_select’][ $post_id ];
    if( ! empty( $select ) ) {
    update_post_meta( $post_id, ‘_select’, esc_attr( $select ) );
    }

    // Checkbox
    $checkbox = isset( $_POST[‘_checkbox’][ $post_id ] ) ? ‘yes’ : ‘no’;
    update_post_meta( $post_id, ‘_checkbox’, $checkbox );

    // Hidden field
    $hidden = $_POST[‘_hidden_field’][ $post_id ];
    if( ! empty( $hidden ) ) {
    update_post_meta( $post_id, ‘_hidden_field’, esc_attr( $hidden ) );
    }
    }

    // Add New Variation Settings
    add_filter( ‘woocommerce_available_variation’, ‘load_variation_settings_fields’ );
    /**
    * Add custom fields for variations
    *
    */
    function load_variation_settings_fields( $variations ) {

    // duplicate the line for each field
    $variations[‘text_field’] = get_post_meta( $variations[ ‘variation_id’ ], ‘_text_field’, true );
    $variations[‘checkbox’] = get_post_meta( $variations[ ‘variation_id’ ], ‘_checkbox’, true );
    $variations[‘text_field’] = get_post_meta( $variations[ ‘variation_id’ ], ‘_number_field’, true );
    $variations[‘select’] = get_post_meta( $variations[ ‘variation_id’ ], ‘_select’, true );

    return $variations;
    }

    ============================================================================
    Added this code to variation.php under wp-plugins/plugins/woocommerce/templates/single-product/add-to-cart/

    {{{ data.variation.text_field }}}

    {{{ data.variation.checkbox }}}

    {{{ data.variation.text_field }}}

    {{{ data.variation.select }}}

    Please help me out with this issue.
    Thanks in Advance.

    1. farlong

      Hi jackdowson1988!
      I have same problem. Did you fix this problem? If yes, please help my.
      Maybe Remi help my?

      Thanks for you help.

  115. michael123

    I am trying to export custom fields data into the email customizer template file.

    Code:
    $product_attr2 = get_post_meta( $product_idMe, ‘_variable_loc’);
    echo var_dump( $product_attr2 );

    My attempt to do this output a blank value; “array(0) { }”
    Note: “$product_idMe” is working, and puts in the correct product ID

    1. michael123

      Additional info:
      $product_idMe = $item->get_product_id();

      I’m thinking part of the issue is not designating the “variation_id”

      Is there a way to do: get_post_meta( $product_idMe,$variations[ ‘variation_id’ ], ‘_variable_loc’);

      1. michael123

        Update: I was able to make some progress by using this:
        $product_variations = new WC_Product_Variable( $product_idMe );
        $product_variations = $product_variations->get_available_variations();
        print_r($product_variations);

        But right now it’s printing out everything, I need a way to just print out the the product variation that was purchased, and just my custom fields.

  116. michael123

    My recent attempts, with no success:

    Attempt#1.
    $product_attr = get_post_meta( $product_variations[$product_idMe] , ‘_variable_mlt’, true );
    echo $product_attr;

    Attempt #2.
    $product_attr = get_post_meta( $product_variations->$product_idMe , ‘_variable_mlt’, true );
    echo $product_attr;
    …………………….

    -Thanks in advance, Michael.

  117. dan1

    Hi Remi, exactly what I needed! Just implemented this in my site and works like a charm. just a little hiccup:

    In the variation.php, I would like to make an “if” statement to print out some html only if the variable contains value, something like this:

    if (!empty(data.variation.number_field)) {

    {{{ data.variation.diameter }}}

    }

    What would be the correct method to do that?

    Thanks so much and great tutorial, learned a lot!

    Daniel

  118. dan1

    sorry the typo, here’s what I’m trying:

    if (!empty(data.variation.diameter)) {

    {{{ data.variation.diameter }}}

    }

  119. dan1

    it looks like I can’t post html here, here’s a picture of what I’m trying to do:
    https://s3.postimg.org/e608q9gs3/Untitled.png

  120. dan1

    Hi Remi
    Great tutorial, thanks a lot!
    I have these minor hiccups:
    1. The fields only shows (on front end) when the variation has a price; If the price is empty the field won’t display; How do I go around that?
    2. How do I create an if statement that outputs the wrapper only if the data.variation.text_field contains data?
    Thanks in advance,
    Daniel

  121. petervp

    hello
    i’m struggling with adding new custom product fields to my WC site.
    basically what I need is to add a new custom sale price block under the general tab (for simple product and variation product), which will contain a text field for the price (this is simple and i’ve managed to do it), but instead of the description, I’d like to add a Schedule button to show another 2 fields for the 2 datepickers (start and end of the offer), just like the default sale price of WC.

    how can I achieve that?
    thanks
    kind regards

  122. supergiu

    Hi Remi,
    first of all thanks a lot for this tutorial.

    Is there a way to make custom fields searchable for product variations?

    I’ve been able to search the custom field for simple products with posts_join and posts_where filters, but for variable products it does not work.

    Can you give me a tip on how to do it?

    Waiting for help
    Thanks

    Giulia

  123. JapeNZ

    Hi Remi,
    I’m currently using a plugin to display all variable products on the front end and am wondering would it be possible to add category selection to product variations, possibly as a custom field?
    So for example say I have a Batman comic with 3 different cover options (1 standard and 2 variations), I put the product in the ‘Batman’ category but would like to have the 2 variant covers in a ‘Batman Cover Variant’ category.
    The front end result being that in all 3 covers are shown in the ‘Batman’ category and only the variations are shown in the ‘Batman Cover Variant’ category.
    I hope you don’t mind me asking.

    Kind regards,
    JP

  124. Simeon-de

    Hi Remi,
    this is cool, How can swap between ‘price’ and ‘custom fields’?
    Waiting for help
    Simeon

  125. ctau@unwembi.co.za

    Hi Remi. Thank you for great tutorial, Do you perhaps know how to display the field in the export csv file using CSV Import Suite.

    1. RebootKidd

      Did you ever find a solution?

  126. […] keep hitting road block after road block I have added custom variations fields in WooCommerce using http://www.remicorson.com/woocommerce-custom-fields-for-variations/ These fields save correctly when updating […]

  127. […] the Remi Coulson tutorial, a custom field has been added for product […]

Leave a Reply