I'm using Add variation setting fields to specific variable products in Woocommerce answer code, to show variation custom fields in WooCommerce, and It's working fine.
Now I would like to hide displayed variation custom fields data when empty. I tried to add this jQuery code:
/* Hide empty custom fields for all variations */
function variation_custom_field_js() {
foreach( custom_fields_settings_all() as $field_key => $values ) {
?>
<script>
jQuery(function($){
var CustomField = "<?php Print($field_key); ?>";
//console.log(CustomField);
$('.shop_attributes .<?php Print($field_key); ?>_class').hide();
$('form.cart').on('show_variation', function(event, data) {
if ( data.<?php Print($field_key); ?> == '0' ) {
$('.shop_attributes .<?php Print($field_key); ?>_class').hide();
} else {
$('.shop_attributes .<?php Print($field_key); ?>_class').show();
}
}).on('hide_variation', function(){
$('.shop_attributes .<?php Print($field_key); ?>_class').hide();
});
});
</script>
<?php
}
}
add_action( 'woocommerce_after_variations_form', 'variation_custom_field_js' );
I can see the script on the frontend, but it doesn't work.
As you don't provide the code that display the custom fields values on selected variations, is not possible to test anything…
Try the following replacement code (not really tested):
It should work.
Here is a complete working example that will display any non-empty custom field, based on the selected variation:
Code goes in functions.php file of your child theme (or in a plugin). Tested and work.
Related: Add variation setting fields to specific variable products in Woocommerce