Show hide custom Woocommerce checkout field based on selected payment method

后端 未结 1 436
温柔的废话
温柔的废话 2020-12-06 23:26

Hi I added custom field in billing form using this code below.

add_filter(\'woocommerce_billing_fields\', \'custom_woocommerce_billing_fields\');

function c         


        
相关标签:
1条回答
  • 2020-12-06 23:47

    The following code will hide billing_options custom optional checkout field when the selected payment method is Cash on delivery ("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;
    }
    

    Code goes in function.php file of your active child theme (or active theme). tested and works.

    0 讨论(0)
提交回复
热议问题