如何在WordPress的WooCommerce我的账户页面添加手机号掩码
在WooCommerce我的账户页面添加手机号掩码功能
方法1:修改账户页面的手机号显示掩码
通过WooCommerce的钩子,在显示用户手机号时自动替换中间部分为星号,实现掩码效果。将以下代码添加到主题的functions.php文件或自定义代码插件中:
// 为我的账户页面的手机号添加显示掩码 add_filter( 'woocommerce_my_account_my_address_formatted_address', 'mask_user_phone_in_account', 10, 3 ); function mask_user_phone_in_account( $formatted_address, $customer_id, $address_type ) { if ( isset( $formatted_address['phone'] ) && !empty( $formatted_address['phone'] ) ) { $phone = $formatted_address['phone']; // 针对11位国内手机号,格式化为XXX****XXXX if ( strlen( $phone ) === 11 ) { $formatted_address['phone'] = substr( $phone, 0, 3 ) . '****' . substr( $phone, 7 ); } else { // 其他长度号码,保留前3位和后3位,中间用*填充 $formatted_address['phone'] = substr( $phone, 0, 3 ) . str_repeat( '*', strlen( $phone ) - 6 ) . substr( $phone, -3 ); } } return $formatted_address; }
方法2:为编辑账户页面添加输入掩码
如果需要用户在编辑手机号时,输入过程中自动生成掩码格式(比如输入时实时替换中间字符),可以添加前端JS脚本:
// 在我的账户页面加载手机号输入掩码脚本 add_action( 'wp_enqueue_scripts', 'enqueue_phone_mask_script' ); function enqueue_phone_mask_script() { if ( is_account_page() ) { wp_add_inline_script( 'jquery', ' jQuery(document).ready(function($) { // 监听手机号输入框,替换为实际字段ID(比如billing_phone/shipping_phone) $("#billing_phone, #shipping_phone").on("input", function() { let value = $(this).val().replace(/\D/g, ""); if (value.length > 3 && value.length <= 7) { value = value.substring(0,3) + "****" + value.substring(3); } else if (value.length >7) { value = value.substring(0,3) + "****" + value.substring(7,11); } $(this).val(value); }); }); ' ); } }
注意事项
- 代码建议使用自定义代码插件(如Code Snippets)添加,避免主题更新时代码丢失。
- 手机号长度和掩码规则可根据需求调整,比如适配国际号码格式。
- 输入框ID需要与实际页面中的字段ID一致,可通过浏览器开发者工具查看确认。
内容的提问来源于stack exchange,提问作者Waji ul hasnanin
相关产品推荐
相关产品推荐

