-
-
Save kloon/4228021 to your computer and use it in GitHub Desktop.
//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; | |
} |
Actually the code provided was working (WC 2.3) !
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.
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 ?
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]);
}
}
}
Hello @shirg!
Did you succeed to display custom field value for each variation on frontend?
Cheers.