如何让已下单的WooCommerce注册客户无法修改结算国家/城市字段
解决WooCommerce结算页国家/城市字段只读问题
你的代码问题在于未添加用户身份与订单状态的判断逻辑,直接对所有用户禁用了字段。要实现仅限制已有订单且已设置地址的用户,需要补充判断逻辑,同时注意禁用字段不会被表单提交,得配合隐藏字段保留原有地址值,避免结算时丢失信息。
以下是修正后的代码:
add_filter('woocommerce_checkout_fields', 'readonly_billing_country_city_for_returning_customers'); function readonly_billing_country_city_for_returning_customers( $fields ) { // 仅针对登录用户处理 if ( is_user_logged_in() ) { $user = wp_get_current_user(); $user_id = $user->ID; // 检查用户是否有已完成的订单 $has_orders = wc_get_customer_order_count( $user_id ) > 0; // 检查用户是否已设置账单国家和城市 $has_billing_country = !empty( $user->billing_country ); $has_billing_city = !empty( $user->billing_city ); // 满足条件则设置字段只读/禁用 if ( $has_orders && $has_billing_country && $has_billing_city ) { // 设置国家字段禁用 $fields['billing']['billing_country']['custom_attributes'] = array( 'disabled' => 'disabled', 'readonly' => 'readonly' ); // 设置城市字段禁用 $fields['billing']['billing_city']['custom_attributes'] = array( 'disabled' => 'disabled', 'readonly' => 'readonly' ); // 添加隐藏字段传递原有值(避免禁用后表单不提交) add_action('woocommerce_after_checkout_billing_form', function() use ($user) { echo '<input type="hidden" name="billing_country" value="' . esc_attr($user->billing_country) . '">'; echo '<input type="hidden" name="billing_city" value="' . esc_attr($user->billing_city) . '">'; }); } } return $fields; }
代码说明:
- 用户范围限制:通过
is_user_logged_in()仅处理登录用户,未登录的新客户可正常修改地址字段。 - 订单状态校验:用
wc_get_customer_order_count()判断用户是否有过历史订单。 - 地址完整性检查:验证用户是否已保存有效的账单国家和城市信息。
- 字段安全处理:给目标字段添加
disabled和readonly属性限制修改;同时添加隐藏字段传递原有地址值,确保结算时地址数据能正常提交到后台。 - 防注入处理:用
esc_attr()转义用户数据,避免XSS安全风险。
如果需要对配送地址(shipping)做同样限制,只需把代码中的billing替换为shipping即可。
内容的提问来源于stack exchange,提问作者Mr Emad Alavi IT
相关产品推荐
相关产品推荐

