WooCommerce结账页账单字段已隐藏,账户地址页仍需隐藏该字段
解决WooCommerce「我的账户」页面账单字段隐藏问题
嗨,我懂你现在的困扰——已经成功把结账页面不需要的账单字段藏起来了,但「我的账户」里的账单地址板块还留着这些字段,对吧?其实只需要给现有代码加个小扩展就能搞定!
问题原因
你之前用的woocommerce_checkout_fields过滤器只作用于结账页面,而「我的账户」页面的地址编辑区域,是由另一个专门的过滤器woocommerce_billing_fields来控制字段显示的,所以之前的代码管不到这里。
完整解决方案代码
我们可以把移除字段的逻辑封装成一个复用函数,同时挂到两个过滤器上,这样结账和账户页面都会生效:
// 封装移除不需要的账单字段的逻辑,避免重复代码 function wc_remove_unwanted_billing_fields( $fields ) { // 移除指定账单字段 unset( $fields['billing_company'] ); unset( $fields['billing_country'] ); unset( $fields['billing_state'] ); unset( $fields['billing_address_1'] ); unset( $fields['billing_address_2'] ); unset( $fields['billing_postcode'] ); return $fields; } // 应用到结账页面 add_filter( 'woocommerce_checkout_fields', 'wc_remove_unwanted_billing_fields' ); // 应用到「我的账户」页面的账单地址编辑区域 add_filter( 'woocommerce_billing_fields', 'wc_remove_unwanted_billing_fields' ); // 单独处理结账页面的订单备注字段(只在结账页生效) function wc_remove_order_comments_field( $fields ) { unset( $fields['order']['order_comments'] ); return $fields; } add_filter( 'woocommerce_checkout_fields', 'wc_remove_order_comments_field' );
为什么这么做?
- 复用函数
wc_remove_unwanted_billing_fields可以避免写两遍相同的移除逻辑,后期维护也更方便。 woocommerce_billing_fields是专门控制账单字段在账户地址编辑页显示的钩子,把移除逻辑挂上去就能让这些字段在账户页也消失。- 订单备注字段只属于结账页面,所以单独用一个小函数处理更清晰。
替换掉你原来的代码,刷新页面后「我的账户」里的账单地址板块就不会再显示那些不需要的字段啦!
内容的提问来源于stack exchange,提问作者Maged Mohamed
相关产品推荐
相关产品推荐

