我正在搜索一段时间以实现我对标题的描述。
这是我现在在子主题的functions.php文件中使用的代码:
//--------------------add custom fields to billing section--------------------------------------------
add_filter( 'woocommerce_checkout_fields' , 'display_checkbox_and_new_checkout_field', 20 );
function display_checkbox_and_new_checkout_field( $fields ) {
$fields['billing']['checkbox_trigger'] = array(
'type' => 'checkbox',
'label' => __('Επιθυμώ Τιμολόγιο', 'woocommerce'),
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['afm_field'] = array(
'label' => __('ΑΦΜ Εταιρείας', 'woocommerce'),
'placeholder' => _x('καταχωρείστε το ΑΦΜ σας...', 'placeholder', 'woocommerce'),
//'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
//toggle feature for the custom field that I need to make required after checkbox is clicked
add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_new_field', 9999 );
function conditionally_hide_show_new_field() {
wc_enqueue_js( "
jQuery('input#checkbox_trigger').change(function(){
if (! this.checked) {
// HIDE IF NOT CHECKED
jQuery('#afm_field_field').hide();
jQuery('#afm_field_field').removeClass('validate-required');
} else {
// SHOW IF CHECKED
jQuery('#afm_field_field').show();
jQuery('#afm_field_field').addClass('validate-required');
}
}).change();
");
}
我也已经尝试了以下方法,但似乎不起作用:
add_filter( 'woocommerce_checkout_process' , 'if_checked_make_afm_required', 20 );
function if_checked_make_afm_required() {
$step = WC()->session->get( 'post_data' );
if ( isset($step['checkbox_trigger']) ) {
$fields['billing']['afm_field']['required'] = true;
} else {
$fields['billing']['afm_field']['required'] = false;
}
}
如果有人可以在这里提供帮助,我将非常感谢。预先感谢!