我正在使用 向 Woocommerce 中的特定变量产品添加变体设置字段 答案代码,以在 WooCommerce 中显示变体自定义字段,并且工作正常。
现在我想在空时隐藏显示的变体自定义字段数据。我尝试添加这个 jQuery 代码:
/* 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' );
我可以在前端看到脚本,但它不起作用。
由于您没有提供显示所选变体的自定义字段值的代码,因此无法测试任何内容......
尝试以下替换代码(未经真正测试):
/* Hide empty custom fields for all variations */
add_action( 'woocommerce_after_variations_form', 'variation_custom_field_js' );
function variation_custom_field_js() {
$field_keys = array_keys( custom_fields_settings_all() );
?>
<script>
jQuery( function($){
<?php foreach( $field_keys as $field_key ) { ?>
$('.shop_attributes .<?php echo $field_key; ?>_class').hide();
<?php } ?>
$('form.cart').on('show_variation', function(event, data) {
<?php foreach( $field_keys as $field_key ) { ?>
console.log(data.<?php echo $field_key; ?>); // To be removed (testing)
if ( data.<?php echo $field_key; ?> !== undefined ) {
$('.shop_attributes .<?php echo $field_key; ?>_class').show();
} else {
$('.shop_attributes .<?php echo $field_key; ?>_class').hide();
}
<?php } ?>
}).on('hide_variation', function(){
<?php foreach( $field_keys as $field_key ) { ?>
$('.shop_attributes .<?php echo $field_key; ?>_class').hide();
<?php } ?>
});
});
</script>
<?php
}
应该可以。