在WooCommerce中检查具有特定模式的结帐帐单号码电话

问题描述 投票:1回答:1

我需要用+370开始生成woocommerce电话号码...我试过这个功能:

add_action('woocommerce_checkout_update_order_meta', 'dd_Testval');

function dd_Testval() {
    $billing_phone = filter_input(INPUT_POST, 'billing_phone');

    if (strlen(trim(preg_replace('[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}', '', $billing_phone))) > 0) {
        wc_add_notice(__('Invalid <strong>Phone Number</strong>, please check your input.'), 'error');
    }
}

它没有任何影响。

有什么建议?

php regex wordpress woocommerce checkout
1个回答
0
投票

正确的方法是:

  • 使用钩在woocommerce_checkout_process动作钩子中的自定义函数代替。
  • 使用preg_match()而不是preg_replace()

现在正则表达式将检查电话号码是否正在+370开始。它将接受以下内容:仅限数字,空格和连字符,最小总长度为9个字符。

add_action('woocommerce_checkout_process', 'custom_checkout_field_process');
function custom_checkout_field_process() {
    // Check the number phone
    if ( isset($_POST['billing_phone']) && ! preg_match("/^(\+370)?[0-9 \-]{5,}/i", $_POST['billing_phone']) )
        wc_add_notice(__('Invalid <strong>Phone Number</strong>, please check your input.'), 'error');
}

此代码位于活动子主题(或主题)的function.php文件中,或者也可以放在任何插件文件中。

经过测试和工作

© www.soinside.com 2019 - 2024. All rights reserved.