You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress WooCommerce结账后为手机号添加摩洛哥国家区号

WooCommerce摩洛哥手机号格式标准化实现代码

以下代码可实现WooCommerce全场景下的摩洛哥手机号自动格式转换,覆盖结账提交、用户中心地址修改、后台订单编辑三个常用场景,完全符合指定转换规则:

/**
 * 标准化摩洛哥手机号格式为212开头无前置0格式
 * @param string $phone 原始手机号
 * @return string 格式化后的手机号
 */
function wc_custom_format_morocco_phone( $phone ) {
    // 移除所有非数字字符
    $clean_phone = preg_replace( '/\D/', '', $phone );
    
    // 匹配不同格式转换
    if ( str_starts_with( $clean_phone, '00212' ) ) {
        // 处理00212开头的国际长途格式
        $formatted = '212' . substr( $clean_phone, 5 );
    } elseif ( str_starts_with( $clean_phone, '212' ) ) {
        // 已带212前缀的格式直接保留
        $formatted = $clean_phone;
    } elseif ( str_starts_with( $clean_phone, '0' ) ) {
        // 处理本地0开头的手机号格式
        $formatted = '212' . substr( $clean_phone, 1 );
    } else {
        // 其他格式兜底,可根据业务需求调整
        $formatted = $clean_phone;
    }
    
    // 校验最终格式为12位212开头的合法手机号,校验失败返回原始值避免错误存储
    return preg_match( '/^212\d{9}$/', $formatted ) ? $formatted : $phone;
}

// 处理结账页面提交的手机号
add_filter( 'woocommerce_checkout_posted_data', 'wc_custom_handle_checkout_phone' );
function wc_custom_handle_checkout_phone( $posted_data ) {
    if ( isset( $posted_data['billing_phone'] ) ) {
        $posted_data['billing_phone'] = wc_custom_format_morocco_phone( $posted_data['billing_phone'] );
    }
    if ( isset( $posted_data['shipping_phone'] ) ) {
        $posted_data['shipping_phone'] = wc_custom_format_morocco_phone( $posted_data['shipping_phone'] );
    }
    return $posted_data;
}

// 处理用户中心地址编辑提交的手机号
add_filter( 'woocommerce_process_myaccount_field_billing_phone', 'wc_custom_format_morocco_phone' );
add_filter( 'woocommerce_process_myaccount_field_shipping_phone', 'wc_custom_format_morocco_phone' );

// 处理后台编辑订单时提交的手机号
add_action( 'woocommerce_process_shop_order_meta', 'wc_custom_handle_admin_order_phone', 10, 2 );
function wc_custom_handle_admin_order_phone( $order_id, $order ) {
    $billing_phone = isset( $_POST['_billing_phone'] ) ? wc_clean( $_POST['_billing_phone'] ) : '';
    if ( $billing_phone ) {
        $order->update_meta_data( '_billing_phone', wc_custom_format_morocco_phone( $billing_phone ) );
    }
    $shipping_phone = isset( $_POST['_shipping_phone'] ) ? wc_clean( $_POST['_shipping_phone'] ) : '';
    if ( $shipping_phone ) {
        $order->update_meta_data( '_shipping_phone', wc_custom_format_morocco_phone( $shipping_phone ) );
    }
    $order->save();
}

注意事项

  • 代码请添加到当前使用主题的functions.php文件末尾,或添加到自定义代码插件中,避免主题更新后代码丢失
  • 代码默认适配PHP 8.0及以上版本,若站点使用PHP 7.x版本,需将所有str_starts_with($字符串, $前缀)替换为兼容写法:0 === strpos($字符串, $前缀)
  • 现有历史订单和用户的手机号不会自动更新,如需批量处理历史数据可自行编写一次性执行的批量处理脚本

内容的提问来源于stack exchange,提问作者Ilyass Benabderrahmane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:06:02