在使用免费送货和统一费率时,如何使 "运送到不同的地址 "被选中?

问题描述 投票:0回答:1

当选择了免费送货或统一费率时,我如何使 "运送到不同的地址 "被选中,如果选择了本地取货,则取消选中。

我所能看到的是所有3种运输方式都被默认选中或不选中。

任何建议将是非常感激的。

感谢

php jquery wordpress woocommerce checkout
1个回答
0
投票

这里是显示隐藏结账运输字段的方法(自动检查取消检查)。"发往不同地址" 复选框,基于所选的送货方式。当选择的运输方式是 "统一费率 "或 "免费送货 "时,它将自动显示运输字段,并隐藏其他运输方式的字段。

// Auto Show hide checkout shipping fields based on chosen shipping methods
add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {
    // Only on checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    // Get shipping methods rates data
    $rates = WC()->session->get('shipping_for_package_0')['rates'];
    $sdata  = []; // Initializing an empty array

    // Loop through shipping methods
    foreach( $rates as $rate ){
        // Targeting only "Flat rate" and "free shipping" shipping methods
        if ( in_array( $rate->method_id, ['flat_rate', 'free_shipping'] ) ) {
            // Add those shipping methods rate Ids in the array
            $sdata[] = $rate->id; 
        } 
    }

    // Jquery code start
    ?>
    <script>
        jQuery(function($){
            var a = 'input[name^="shipping_method"]',               b = a+':checked',
                c = 'input#ship-to-different-address-checkbox',
                d = <?php echo json_encode( $sdata ); ?>;

            // Conditional function that checks if the chosen shipping method enables "shipping fields"
            function rateIdEnableCheckbox( rateID, d ) {
                var e = false;

                // Loop through all available shipping methods Ids
                $.each( d, function( k, v ){
                    if( rateID == v ){
                        e = true;
                    }
                });

                return e;
            }

            // function that show or hide shipping address fields (checkbox)
            function showHideShippingAddressFields( b, c, d ) {
                var f = $(c).prop("checked") ? true : false,
                    g = rateIdEnableCheckbox( $(b).val(), d );

                if ( ( g && ! f ) || ( ! g && f ) ) {
                    $(c).click(); // Clik the checkbox (show hide shipping address)
                }
                // console.log($(b).val());
            }

            // 1. On load, the chosen shipping method
            setTimeout(function(){
                showHideShippingAddressFields( b, c, d );
            }, 100);

            // 2. On change shipping method (Live event)
            $( 'form.checkout' ).on( 'change', a, function() {
                showHideShippingAddressFields( b, c, d );
            });
        });
    </script>
    <?php
    endif;
}

代码在活动的子主题(或活动主题)的function.php文件中。经过测试,工作。

© www.soinside.com 2019 - 2024. All rights reserved.