如何禁用 WooCommerce 结帐中预填的字段?

How to disable fields that are pre-filled in WooCommerce checkout?

我想阻止(例如,将这些字段设置为只读)用户更改他们在 WooCommerce 结帐表单上的账单信息。

我目前正在使用这个代码片段:

add_filter('woocommerce_billing_fields', 'mycustom_woocommerce_billing_fields', 10, 1 );
function mycustom_woocommerce_billing_fields($fields)
{
   $fields['billing_first_name']['custom_attributes'] = array('readonly'=>'readonly');
   $fields['billing_last_name']['custom_attributes'] = array('readonly'=>'readonly');
   $fields['billing_email']['custom_attributes'] = array('readonly'=>'readonly');
   $fields['billing_phone']['custom_attributes'] = array('readonly'=>'readonly');
   return $fields;
}

但问题是:如果用户在注册时没有填写任何这些字段,他将无法在结帐表单中插入他的数据,因为这些字段是不可编辑。

我的问题是: 如果字段不为空,如何使它们只读(或禁用)

谁能帮我解决这个问题?

我相信这就是你要找的,评论并在代码中添加解释

function mycustom_woocommerce_billing_fields( $fields ) {   
    // Get current user
    $user = wp_get_current_user();

    // User id
    $user_id = $user->ID;

    // User id is found
    if ( $user_id > 0 ) { 
        // Fields
        $read_only_fields = array ( 'billing_first_name', 'billing_last_name', 'billing_email', 'billing_phone' );

        // Loop
        foreach ( $fields as $key => $field ) {     
            if( in_array( $key, $read_only_fields ) ) {
                // Get key value
                $key_value = get_user_meta($user_id, $key, true);

                if( strlen( $key_value ) > 0 ) {
                    $fields[$key]['custom_attributes'] = array(
                        'readonly'=>'readonly'
                    );
                }
            }
        }
    }

   return $fields;
}
add_filter('woocommerce_billing_fields', 'mycustom_woocommerce_billing_fields', 10, 1 );

7uc1f3r 的答案当然可以获取用户数据……但是从 WooCommerce 3 开始,您可以使用 WC_Checkout get_value() dedicated method 如下:

add_filter( 'woocommerce_billing_fields', 'filter_wc_billing_fields', 10, 1 );
function filter_wc_billing_fields( $fields ) {
    // On checkout and if user is logged in
    if ( is_checkout() && is_user_logged_in() ) {
        // Define your key fields below
        $keys_fields = ['billing_first_name', 'billing_last_name', 'billing_email', 'billing_phone'];

        // Loop through your specific defined fields
        foreach ( $keys_fields as $key ) {
            // Check that a value exist for the current field
            if( ( $value = WC()->checkout->get_value($key) ) && ! empty( $value ) ) {
                // Make it readonly if a value exist
                $fields[$key]['custom_attributes'] = ['readonly'=>'readonly'];
            }
        }
    }
    return $fields;
}

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

如果您希望此代码在“我的帐户”>“地址”>“编辑...”中也处于活动状态,您只需从第一个 IF[=23 中删除 is_checkout() && =]声明。