根据运输方式,使用 woocommerce 删除选定的结帐字段

use*_*105 2 wordpress woocommerce

您好,我正在尝试弄清楚如何根据所选的运输方式使用 woocommerce 结帐删除一些计费字段。因此,使用此代码,当客户选择本地送货时,我尝试取消设置帐单地址、帐单城市、帐单州和帐单邮政编码,但此代码不起作用。任何帮助,将不胜感激。

add_filter('woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields');

function xa_remove_billing_checkout_fields($fields) {
$shipping_method ='local_pickup:1'; // Set the desired shipping method to hide the checkout field(s).

global $woocommerce;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];

if ($chosen_shipping == $shipping_method) {
    unset($fields['billing']['billing_address_1']); // Add/change filed name to be hide
    unset($fields['billing']['billing_address_2']);
    unset($fields['billing']['billing_city']);
    unset($fields['billing']['billing_state']);
    unset($fields['billing']['billing_postcode']);
}
return $fields;
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*gel 6

以下是我将如何解决这个问题。
这将涉及到 php、css 和 javascript (jQuery)。

PHP

add_filter( 'woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields( $fields ) {
    // change below for the method
    $shipping_method ='local_pickup:1'; 
    // change below for the list of fields
    $hide_fields = array( 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode' );

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    // uncomment below line and reload checkout page to check current $chosen_methods
    // print_r($chosen_methods);
    $chosen_shipping = $chosen_methods[0];

    foreach($hide_fields as $field ) {
        if ($chosen_shipping == $shipping_method) {
            $fields['billing'][$field]['required'] = false;
            $fields['billing'][$field]['class'][] = 'hide';
        }
        $fields['billing'][$field]['class'][] = 'billing-dynamic';
    }

    return $fields;
}
Run Code Online (Sandbox Code Playgroud)

我们不会取消这些字段,而只是改变它的required性质。这意味着,如果所选方法是我们想要检查的方法,我们不会将其设为必需。然后我们将添加一个hide类。这样,我们就可以使用 css 隐藏这些字段。并且 woocommerce 不会抛出所需的错误。使用 jQuery,我们可以显示/隐藏这些字段。因此,如果我们在第一次运行时取消设置它,则不会显示任何内容,因为这些字段一开始就不存在,因此页面需要重新加载。

这是 javascript 和 css 部分。

add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
    if (is_checkout()) :
    ?>
    <style>
        .hide {display: none!important;}
    </style>
    <script>
        jQuery( function( $ ) {

            // woocommerce_params is required to continue, ensure the object exists
            if ( typeof woocommerce_params === 'undefined' ) {
                return false;
            }

            $(document).on( 'change', '#shipping_method input[type="radio"]', function() {
                // change local_pickup:1 accordingly 
                $('.billing-dynamic').toggleClass('hide', this.value == 'local_pickup:1');
            });
        });
    </script>
    <?php
    endif;
}
Run Code Online (Sandbox Code Playgroud)