Skip to content

Instantly share code, notes, and snippets.

@kloon
Created December 6, 2012 20:25
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save kloon/4228021 to your computer and use it in GitHub Desktop.
Save kloon/4228021 to your computer and use it in GitHub Desktop.
WooCommerce variations custom field
//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;
}
@moorewebx
Copy link

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!!!

@jjdualan
Copy link

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

@DesignByOnyx
Copy link

@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.

@vssnarayanaraju
Copy link

I have used the above code but not getting field values in front end

@egmi
Copy link

egmi commented Jun 26, 2014

I want to display the custom fields on the cart and checkout page. How does it work?

@sarc85
Copy link

sarc85 commented Jul 3, 2014

I have also used the code above and it is pulling the values but they are not printing in the div

@meilione
Copy link

meilione commented Aug 5, 2014

To add the custom variation meta data also to the fronted variations variable use the following filter (bit less code than mentioned above and the data is added directly to the already existing json output).

<?php
add_filter( 'woocommerce_available_variation', 'uniquename_available_variation', 100, 3 );

function uniquename_available_variation($variations, $variation_object, $variation) {
    $variations['yourcustomfieldname'] = implode(',',$variation->product_custom_fields['yourcustomfieldname']);
    return $variations;
}
?>

Note: the implode is optional and depends on how you want to use the data later on

@DesignByOnyx
Copy link

Unfortunately I'm not in a position I can test this right now (super busy, not even working in Wordpress at the moment). If you could post a live example I might be able to look at it for you. Otherwise you might try looking at the javascript I posted and troubleshoot from there. Grab a beer, as that was not fun to write.

@Justlikefrank
Copy link

Thanks so much @DesignByOnyx you have done a great job.
I have got the fields into the front end which is awesome, However I can't get content to work in them? I was wondering if they needed to be defined somehow? I don't have much code experience and was just hoping anyone can take a quick look at where I am at.
The fields created are the highlighted in pink, I'm after two things,

  1. The content and editability, and
  2. is the order in which they show?
    Any suggestions will be greatly appreciated...
    http://www.staging.theflowerrun.com.au/product/flower-run-bunch/

@whoaloic
Copy link

I also used the code provided by @DesignByOnyx but can't get custom field values of single product variation.
I notice that even the comment " Holds the value for the variation custom field " disappeared when I use firebug.

@whoaloic
Copy link

Hello
I did see an array of custom field values with firebug but i still can't find a way to display custom field values.
Any help would be really appreciated.
Regards.

@shirg
Copy link

shirg commented Apr 28, 2015

If someone else is stuck, here is a code modification that solves the problem when variable data is not saved or displayed correctly. This is a short example, with just the number field. To be honest, I'm not sure if the JS part is needed at all. and please also note that I have tested it on WC 2.3.5

// Number Field woocommerce_wp_text_input( array( 'id' => '_purchase_price['.$loop.']', 'label' => __( 'Purchase Price', 'woocommerce' ), 'value' => get_post_meta($variation->ID, '_purchase_price', true), 'custom_attributes' => array( 'step' => 'any', 'min' => '0' ) ) ); ?> </td> '_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' ) ) ); ?>

@whoaloic
Copy link

Hello @shirg!
Did you succeed to display custom field value for each variation on frontend?
Cheers.

@whoaloic
Copy link

whoaloic commented Jul 2, 2015

Actually the code provided was working (WC 2.3) !

@Bgill128
Copy link

Bgill128 commented Jul 3, 2015

Hey @whoaloic

I really cannot figure out how to get the Remicorson snippets or anything like that to show up on the FRONT of my site. I saw in his tutorial he had a tiny note about it and some other people have been figuring out but I just cannot.

@wylesight
Copy link

Yes, displaying in the front is the issue: I can display custom meta values when there's only one variation.

When products have multiple variable attributes the meta display but it is WRONG : it only display the first value found with the selected attribute, not taking into account the full variation.

Any idea ?

@josefrosel
Copy link

That worked for me:
Use the woocommerce_ajax_save_product_variations and change the variable_fields_process function.

//Save variation fields
add_action('woocommerce_ajax_save_product_variations', 'variable_fields_process', 10, 2);

function variable_fields_process($product_id) {
$variable_post_id = $_POST['variable_post_id'];
$variable_custom_field = $_POST['my_custom_field'];

foreach ($variable_post_id as $key => $value) {
    if (isset($_POST['my_custom_field'][$key])) {
        update_post_meta($value, 'my_custom_field', $variable_custom_field[$key]);
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment