如果复选框被勾选,如何使WooCommerce结账字段变为非必填?

4
在WordPress Woocommerce的结账页面中,如果选中“公司购买”复选框,我希望使“billing_name”字段非必填。
我已经成功隐藏了结账页面中的“billing_name”字段,但如何使其也非必填?
add_filter( 'woocommerce_checkout_fields' , 'company_checkbox_and_new_checkout_fields', 9999 );
  

function company_checkbox_and_new_checkout_fields( $fields ) {
    
$fields['billing']['buy_on_company'] = array( // CSS ID
    'type'      => 'checkbox',
    'label'     => __('Buy on company', 'woocommerce'),
    'class'     => array('form-row-wide'), // CSS Class
    //'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
    'clear'     => true,
    'priority'  => '10'
);   

    $fields['billing']['billing_name']['placeholder'] = 'First Name Last name';

return $fields;
}

function hook_javascript() {
  ?>
  <script>
        document.getElementById('buy_on_company').onclick = function () {
            if (this.checked) {
                document.getElementById('billing_name').style['display'] = 'none';
            } else {
                document.getElementById('billing_name').style['display'] = 'block';
            }

        };
  </script>
  <?php
}

add_action( 'woocommerce_after_checkout_form', 'hook_javascript' );
1个回答

1

我已经完成了这个:

add_filter( 'woocommerce_checkout_fields' , 'company_checkbox_and_new_checkout_fields_1', 9999 );
function company_checkbox_and_new_checkout_fields_1( $fields ) {
        if (isset($_POST['buy_on_company'])) {          
            $fields['billing']['billing_name']['required'] = false;
            } else {
            $fields['billing']['billing_name']['required'] = true;  
        }
return $fields;
}

现在它不要求填写账单名称字段。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接