如何无误地删除所有 Woocommerce 结账账单字段

How to remove all Woocommerce checkout billing fields without errors

该操作有助于使字段成为非必填字段

add_filter( 'woocommerce_checkout_fields', 'unrequire_checkout_fields' );
function unrequire_checkout_fields( $fields ) {
  $fields['billing']['billing_company']['required']   = false;
  $fields['billing']['billing_city']['required']      = false;
  $fields['billing']['billing_postcode']['required']  = false;
  $fields['billing']['billing_country']['required']   = false;
  $fields['billing']['billing_state']['required']     = false;
  $fields['billing']['billing_address_1']['required'] = false;
  $fields['billing']['billing_address_2']['required'] = false;
  return $fields;
}

但它只适用于 css

#billing_country_field, #billing_address_1_field, #billing_address_2_field,#billing_state_field,#billing_last_name_field,#billing_postcode_field,#billing_company_field {
        display: none !important; }

我认为这不是最好的决定。一定是这样

add_filter('woocommerce_checkout_fields','remove_checkout_fields');
function remove_checkout_fields($fields){
    unset($fields['billing']['billing_first_name']);
    unset($fields['billing']['billing_last_name']);
    unset($fields['billing']['billing_address_1']);
    unset($fields['billing']['billing_address_2']);
    unset($fields['billing']['billing_city']);
    unset($fields['billing']['billing_postcode']);
    unset($fields['billing']['billing_country']);
    unset($fields['billing']['billing_state']);
    return $fields;
}

但是,当我准确地添加该代码时,它需要地址,并说支付方式(本地本地取货)是错误的。没有该代码并使用 css 一切正常。也许有人有同样的问题并且已经解决了?尽可能不使用插件。

这需要以不同的方式完成,因为在真实世界中 WooCommerce 要求结帐账单国家抛出错误,如 “请输入地址以继续。”:

为避免此问题,请改用以下内容(您将在其中定义要删除的所有关键字段)

// Just hide woocommerce billing country
add_action( 'woocommerce_before_checkout_form', 'hide_checkout_billing_country', 5 );
function hide_checkout_billing_country() {
    echo '<style>#billing_country_field{display:none;}</style>';
}

add_filter('woocommerce_billing_fields', 'customize_checkout_fields', 100 );
function customize_billing_fields( $fields ) {
    if ( is_checkout() ) {
        // HERE set the required key fields below
        $chosen_fields = array('first_name', 'last_name', 'address_1', 'address_2', 'city', 'postcode', 'country', 'state');

        foreach( $chosen_fields as $key ) {
            if( isset($fields['billing_'.$key]) && $key !== 'country') {
                unset($fields['billing_'.$key]); // Remove all define fields except country
            }
        }
    }
    return $fields;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。