public
Last active

WooCommerce variations custom field

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
//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', 'variable_fields_process', 10, 1 );
 
function variable_fields( $loop, $variation_data ) {
?>
<tr>
<td>
<div>
<label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>
<input type="text" size="5" name="my_custom_field[<?php echo $loop; ?>]" value="<?php echo $variation_data['_my_custom_field'][0]; ?>"/>
</div>
</td>
</tr>
<?php
}
 
function variable_fields_js() {
?>
<tr>\
<td>\
<div>\
<label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>\
<input type="text" size="5" name="my_custom_field[' + loop + ']" />\
</div>\
</td>\
</tr>\
<?php
}
 
function variable_fields_process( $post_id ) {
if (isset( $_POST['variable_sku'] ) ) :
$variable_sku = $_POST['variable_sku'];
$variable_post_id = $_POST['variable_post_id'];
$variable_custom_field = $_POST['my_custom_field'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $variable_custom_field[$i] ) ) {
update_post_meta( $variation_id, '_my_custom_field', stripslashes( $variable_custom_field[$i] ) );
}
endfor;
endif;
}

Hello. This is JUST what I was looking for. Thank you so much. Do you have any code fore displaying the field on the front end, and changing based on the variation selection being changed? That would be amazing. Thanks!

Hello. Where I insert this into woocommerce?

Thanks @kloon. Very useful. :)

@bizard, you can insert code into your active theme's function file.

This is awesome, Is there away to show this with the other variation fields under additional info on front-end?

That's what I needed, thanks, and it works.
but.. how to show the field on front-end too?
I think the right file is variable.php, but how to write the code in order to add the "my_custom_field"? I cannot manage.
Any help, please??
thanks
harassant

That's exactly what I am looking for. Because I'm new to WooCommerce I don't know how to show the content of "my_custom_fields" on the frontpage. Hopefully anybody can post some example. Thanks!

so i'm not alone!
hi tmconnect
I made some progress, but could not yet obtain a solution.
I've been working on this file:
woocommerce\templates\single-product\meta.php
and on this piece of code:
span class="sku"><?php echo $product->get_sku();?>/span
and on the table "wp_postmeta" in db, where "my_custom_field" values are stored.
The variable $product->get_sku(); by itself refers to the parent sku, but the class "sku" makes it show the variations sku, exactly the value I need in order to get the "my_custom_field" post_id and consequently it's meta_value
(meta_key being "_my_custom_field").

It would be easy to retrieve dinamically each single variation my_custom_field value through some queries like these:
$alfa = $wpdb->get_var( "SELECT post_id FROM wp_postmeta WHERE meta_key = '_sku' AND meta_value = single variation sku' ", 0, 0 );
and
$my_custom_field_value = $wpdb->get_var( "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_my_custom_field' AND post_id = '$alfa' ", 0, 0 );.

The problem is that I'm not able to convert the markup span class="sku"><?php echo $product->get_sku(); ?>/span (that renders on frontend the variation sku I need) into a string usable in the first query as 'single variation sku'.

This stupid problem solved, THE PROBLEM solved.

Any idea??
bye
ruggero

I cant for the life of me figure out how to get the custom fields to display on the product descriptions or which file to edit to get it to do so. Has anyone figured this out? Please help. This problem is causing a lot of stress. Thanks in advance.

Hey man. i cant get the product fields to save??? I just copied and pasted what you have here. The fields shows, but the value doesn't save

Any news here?

The function is exactly what I need. But I also have problems to show the custom field content in the front end.

I put the above code in my function.php and in the backend everything is fine. I guess to show the custom field content in the front end I need to something like <?php echo... in meta.php

Please help!!!

Something like this should help get you started on your variable product template:

<?php 
global $product; 
$available_variations = $product->get_available_variations();
?>

<?php 
foreach ($available_variations as $prod_variation) :
    $post_id = $prod_variation['variation_id'];
    $post_object = get_post($post_id);
    $my_custom_field = get_post_meta( $post_object->ID, '_my_custom_field', true);
end foreach;
?>

So here is some code which will work with the default Variable Product template which ships with WooCommerce. This is a little more difficult than it should be, so here is the step-by-step.

  1. Copy this file:

    /wp-content/plugins/woocommerce/templates/single-product/add-to-cart/variable.php

    to your theme's folder:

    /wp-content/themes/YOUR_THEME/woocommerce/single-product/add-to-cart/variable.php

  2. Open the file you just copied and add a new DIV just inside the <form> tag:

    <form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo $post->ID; ?>" data-product_variations="<?php echo esc_attr( json_encode( $available_variations ) ) ?>">
        <?php if ( ! empty( $available_variations ) ) : ?>
            <div class="selected-variation-custom-field"><!-- Holds the value for the variation custom field --></div>
    
  3. Next, add the following PHP right after the DIV above. This builds a list of our variation IDs and the custom field values. We will json_encode this information to use in the next step:

    <?php
    $custom_data = array();
    foreach ($available_variations as $prod_variation) :
        // get some vars to work with
        $variation_id = $prod_variation['variation_id'];
        $variation_object = get_post($variation_id);
        $custom_field = get_post_meta( $variation_object->ID, '_my_custom_field', true);
    
        $custom_data[$variation_id] = array(
            "custom_field_value" => $custom_field
        );
    endforeach;
    ?>
    
  4. Next, past this javascript after the PHP from the last step:

    <script>
    jQuery(function($) {
        var variation_custom_fields = <?php echo json_encode($custom_data); ?>,
            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 );
        });
    });
    </script>
    
  5. Use the following CSS to style the information:

    .selected-variation-custom-field {
        /* styles here */
    }
    
  6. Post back here and let everybody know how it works. Cheers.

Dude... you nailed it. Thanks so much for this, much appreciated!

So I got this working and it works just like I want. thank you. I have two follow up questions:
1) How would I add a label that shows up in front only when the custom field value shows up
2) How would I implement multiple custom fields without having to re-do all of that same code each time? (I assume there is an easy way)
thanks again!!!

Thanks so much for the code. I was wondering if this info will automatically be shown on invoices. If not, could you point me in a general direction?

Thanks again

@moorewebx

1) I am not sure what you are asking. The custom field is tied to a variation (eg. shoe size). When the end user selects a shoe size which is using the custom field, you should see it show up. For example, here is a product using the custom field, and here is a product which is not using the custom field. The custom field only appears when there is actually a value in there.

2) Implementing multiple custom fields would look something like this:

  • functions.php - take note of every instance of the word "another"
<?php
//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', 'variable_fields_process', 10, 1 );

function variable_fields( $loop, $variation_data ) {
?>  
    <tr>
        <td>
            <div>
                    <label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>
                    <input type="text" size="5" name="my_custom_field[<?php echo $loop; ?>]" value="<?php echo $variation_data['_my_custom_field'][0]; ?>"/>
            </div>
        </td>
    </tr>
    <tr>
        <td>
            <div>
                    <label><?php _e( 'Another Field', 'woocommerce' ); ?></label>
                    <input type="text" size="5" name="another_field[<?php echo $loop; ?>]" value="<?php echo $variation_data['_another_field'][0]; ?>"/>
            </div>
        </td>
    </tr>
<?php
}

function variable_fields_js() {
?>
    <tr>\
        <td>\
            <div>\
                    <label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>\
                    <input type="text" size="5" name="my_custom_field[' + loop + ']" />\
            </div>\
        </td>\
    </tr>\
    <tr>\
        <td>\
            <div>\
                    <label><?php _e( 'Another Field', 'woocommerce' ); ?></label>\
                    <input type="text" size="5" name="another_field[' + loop + ']" />\
            </div>\
        </td>\
    </tr>\
<?php
}

function variable_fields_process( $post_id ) {
    if (isset( $_POST['variable_sku'] ) ) :
        $variable_sku = $_POST['variable_sku'];
        $variable_post_id = $_POST['variable_post_id'];
        $variable_custom_field = $_POST['my_custom_field'];
        $variable_another_field = $_POST['another_field'];

        for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
            $variation_id = (int) $variable_post_id[$i];
            if ( isset( $variable_custom_field[$i] ) ) {
                update_post_meta( $variation_id, '_my_custom_field', stripslashes( $variable_custom_field[$i] ) );
            }
            if ( isset( $variable_another_field[$i] ) ) {
                update_post_meta( $variation_id, '_another_field', stripslashes( $variable_another_field[$i] ) );
            }
        endfor;
    endif;
}
?>
  • [theme]/woocommerce/single-product/add-to-cart/variable.php - add another DIV
<div class="selected-variation-custom-field"><!-- Holds the value for the variation custom field --></div>
<div class="selected-variation-another-field"><!-- Holds the value for the variation another field --></div>
  • Update the PHP code in the same file:
<?php
$custom_data = array();
foreach ($available_variations as $prod_variation) :
    // get some vars to work with
    $variation_id = $prod_variation['variation_id'];
    $variation_object = get_post($variation_id);
    $custom_field = get_post_meta( $variation_object->ID, '_my_custom_field', true);
    $another_field = get_post_meta( $variation_object->ID, '_another_field', true);

    $custom_data[$variation_id] = array(
        "custom_field_value" => $custom_field,
        "another_field_value" => $another_field
    );
endforeach;
?>
  • Update the javascript (same file)
<script>
jQuery(function($) {
    var variation_custom_fields = <?php echo json_encode($custom_data); ?>,
        variations_data = JSON.parse( $('form.variations_form').first().attr( 'data-product_variations' ) ),
        $selected_variation_custom_field = $('.selected-variation-custom-field'),  // see DIV above
        $selected_variation_another_field = $('.selected-variation-another-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 = "",
            another_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;
                another_field_value = variation_custom_fields[ this.variation_id ].another_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 );
        $selected_variation_another_field.text( another_field_value );
    });
});
</script>
  • And finally, the styles:
.selected-variation-custom-field {
    /* styles here */
}
.selected-variation-another-field {
    /* styles here */
}

If you want to add even more custom fields, take note of everywhere the word "another" appears (case insensitive), copy and paste, and change it to something unique. Hope that helps.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.