根据所选付款方式显示隐藏自定义 Woocommerce 结账字段

sol*_*tal 3 php wordpress jquery checkout woocommerce

您好,我使用下面的代码在计费表单中添加了自定义字段。

\n\n
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');\n\nfunction custom_woocommerce_billing_fields($fields)\n{\n\n    $fields['billing_options'] = array(\n        'label' => __('If you pay by Invoice. Please add Your Invoice Number Here ', 'woocommerce'), // Add custom field label\n        'placeholder' => _x('Invoice Number', 'placeholder', 'woocommerce'), // Add custom field placeholder\n        'required' => false, // if field is required or not\n        'clear' => false, // add clear or not\n        'type' => 'text', // add field type\n        'class' => array('my-css')    // add class name\n    );\n\n    return $fields;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我有两种付款方式 1. 货到付款 2.Realex Payments HPP \xe2\x80\x93 信用卡。

\n\n

是否可以仅在 1. 选择货到付款作为付款选项时显示自定义字段?

\n\n

谢谢

\n

Loi*_*tec 5

billing_options当所选付款方式为货到付款(“cod”)时,以下代码将隐藏自定义可选结帐字段:

// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
    // Only on checkout page
     if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script>
        jQuery(function($){
            var a = 'input[name="payment_method"]',
                b = a + ':checked',
                c = '#billing_options_field'; // The checkout field <p> container selector

            // Function that shows or hide checkout fields
            function showHide( selector = '', action = 'show' ){
                if( action == 'show' )
                    $(selector).show( 200, function(){
                        $(this).addClass("validate-required");
                    });
                else
                    $(selector).hide( 200, function(){
                        $(this).removeClass("validate-required");
                    });
                $(selector).removeClass("woocommerce-validated");
                $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
            }

            // Initialising: Hide if choosen payment method is "cod"
            if( $(b).val() !== 'cod' )
                showHide( c, 'hide' );
            else
                showHide( c );

            // Live event (When payment method is changed): Show or Hide based on "cod"
            $( 'form.checkout' ).on( 'change', a, function() {
                if( $(b).val() !== 'cod' )
                    showHide( c, 'hide' );
                else
                    showHide( c );
            });
        });
    </script>
    <?php
    endif;
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题的functions.php 文件中(或插件中)。经过测试并有效。

新的类似答案:
根据所选付款方式启用/禁用 WooCommerce 所需的结账字段