基于运输方式的必填结帐字段 - Woocommerce

Required Checkout Field Based on Shipping Method - Woocommerce

如果选择本地取货,我想 billing_last_name 不需要。

尝试这样的事情:

function xa_remove_billing_checkout_fields($fields) {
    $shipping_method ='local_pickup'; // 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) {
       $fields['billing']['billing_last_name'][ 'required' ] = false;
    }
    return $fields;
}

但它不起作用。

有没有合适的解决办法?

这是您更新后的带有钩子的代码:

add_filter('woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields');

function xa_remove_billing_checkout_fields($fields) {
    $shipping_method ='local_pickup'; // 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) {
       $fields['billing']['billing_last_name'][ 'required' ] = false;
    }
    return $fields;
}