如果选中自定义复选框,WooCommerce Checkout 会为账单字段添加默认值

WooCommerce Checkout add default value to Billing fields if custom checkbox checked

我已经在结帐页面中创建了一个名为 billng_anonymouse 的自定义复选框字段,现在我希望当客户选中此复选框时它应该添加默认值为 billing_first_namebilling_last_name.

目前,我正在使用此功能为账单字段添加默认值

function zk_set_checkout_field_input_value_default($fields) {
    $fields['billing']['billing_first_name']['default'] = 'First';
    $fields['billing']['billing_last_name']['default'] = 'Last';
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'zk_set_checkout_field_input_value_default' );

但问题是默认值始终存在,如何仅在选中复选框时使用 IF 函数显示它们。

您可以在 woocommerce_checkout_fields 中使用 custom_attributes,这样您就可以在属性中存储一个值,以便在复选框选中和取消选中时使用。试试下面的代码。

function zk_set_checkout_field_input_value_default($fields) {
    $fields['billing']['billing_first_name']['custom_attributes'] = array( 'data-default' => 'First' );
    $fields['billing']['billing_last_name']['custom_attributes'] = array('data-default'=>'Last' );
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'zk_set_checkout_field_input_value_default' );

function add_custom_checkout_field( $checkout ) { 
    $current_user = wp_get_current_user();
    $billng_anonymouse = $current_user->billng_anonymouse;
    woocommerce_form_field( 'billng_anonymouse', array(        
        'type'  => 'checkbox',        
        'class' => array( 'form-row-wide' ),        
        'label' => 'Billng anonymouse'
    ), $checkout->get_value( 'billng_anonymouse' ) ); 
}
add_action( 'woocommerce_before_checkout_billing_form', 'add_custom_checkout_field' );

function add_custom_js(){
    ?>
    <script type="text/javascript">
        (function($){
            $(document).on('change', '#billng_anonymouse', function(event) {
                if( $(this).is(':checked') ){
                    $('#billing_first_name').val($('#billing_first_name').data('default'));
                    $('#billing_last_name').val($('#billing_last_name').data('default'));
                }else{
                    $('#billing_first_name').val('');
                    $('#billing_last_name').val('');
                }
            });
        })(jQuery);
    </script>
    <?php
}
add_action( 'woocommerce_after_checkout_form', 'add_custom_js', 10, 1 );

已测试并有效。