我想向 WooCommerce 结账页面电话号码添加自定义验证:
这是我到目前为止所拥有的代码:
add_action('woocommerce_checkout_process', 'njengah_custom_checkout_field_process');
function njengah_custom_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error. This one is only requite for companies
if ( ! (preg_match('/^[0-9]{10}$/D', $_POST['billing_phone'] ))){
wc_add_notice( "Incorrect Phone Number! Please enter valid 10 digits phone number" ,'error' );
}
}
尝试以下(使用
strpos()
定位 2 位起始数字):
add_action('woocommerce_checkout_process', 'custom_checkout_field_process');
function custom_checkout_field_process() {
if ( isset($_POST['billing_phone']) && ! empty($_POST['billing_phone']) ) {
$phone = $_POST['billing_phone'];
if ( strpos($phone,'02') === 0 && ! preg_match('/^[0-9]{9}$/D', $phone ) ) {
wc_add_notice( 'Incorrect Phone Number! Please enter valid 9 digits phone number', 'error' );
}
elseif ( strpos($phone,'08') === 0 && ! preg_match('/^[0-9]{10}$/D', $phone ) ) {
wc_add_notice( 'Incorrect Phone Number! Please enter valid 10 digits phone number', 'error' );
}
}
}