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

ale*_*rey 2 php wordpress woocommerce hook-woocommerce woocommerce-checkout-fields

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

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;
}
Run Code Online (Sandbox Code Playgroud)

但它只适用于 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; }
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我准确添加该代码时,它需要地址并表示付款方式(本地本地取货)是错误的。没有该代码并且使用 css 一切都可以正常工作。也许有人遇到了同样的问题并且已经解决了?如果可以的话不用插件。

Loi*_*tec 6

这需要以不同的方式完成,就像在实际情况中,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_billing_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;
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。