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 (source)
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) {
?>
<tr>
<td>
<?php
// Select
woocommerce_wp_select(
array(
'id' => '_select[' . $loop . ']',
'label' => __('My Select Field', 'woocommerce'),
'description' => __('Choose a value.', 'woocommerce'),
'value' => $variation_data['_select'][0],
'options' => array(
'one' => __('Option 1', 'woocommerce'),
'two' => __('Option 2', 'woocommerce'),
'three' => __('Option 3', 'woocommerce')
)
)
);
?>
</td>
</tr>
<?php
}
/**
* Create new fields for new variations
*
*/
function variable_fields_js() {
?>
<tr>
<td>
<?php
// Select
woocommerce_wp_select(
array(
'id' => '_select[ + loop + ]',
'label' => __('My Select Field', 'woocommerce'),
'description' => __('Choose a value.', 'woocommerce'),
'value' => $variation_data['_select'][0],
'options' => array(
'one' => __('Option 1', 'woocommerce'),
'two' => __('Option 2', 'woocommerce'),
'three' => __('Option 3', 'woocommerce')
)
)
);
?>
</td>
</tr>
<?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
$_select = $_POST['_select'];
for ($i = 0; $i < sizeof($variable_sku); $i++) :
$variation_id = (int) $variable_post_id[$i];
if (isset($_select[$i])) {
update_post_meta($variation_id, '_select', stripslashes($_select[$i]));
}
endfor;
// Checkbox
endif;
}
It all saving correctly but in the front end i can’t get the value of the corresponding variation but i am still finding a solution.
Like in a front end if you change the variation it changing the price simultaneously. I am want to display another information on top of the variation price. Is that possible to do in woocommerce.
Here is the screenshot.
Backend Variable Product
Expected Output in Front End
How to show the custom field data on changing the list box?
brasofilo,
I wrote a tutorial/example on this issue here:
http://blueskysessions.com/2014/03/31/woocommerce-display-dynamic-content-per-the-selected-product-variation/
I had the same question and figured out a way to do it.
This is not as simple as one might think. It requires a little bit of everything but ultimately the trick lies in using jQuery to show and hide content.