我想向 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' );
}
}
使用以下代码,如果输入的电话号码会抛出错误消息,避免结账:
代码:
add_action('woocommerce_checkout_process', 'custom_checkout_billing_phone_validation');
function custom_checkout_billing_phone_validation() {
if ( isset($_POST['billing_phone']) && ! empty($_POST['billing_phone']) ) {
$phone = str_replace(' ', '', $_POST['billing_phone']);
$length = strlen($phone);
// Number starting with "02" with more digits than 9
if ( strpos($phone,'02') === 0 && is_numeric($phone) && $length > 9 ) {
wc_add_notice( __('Incorrect Phone Number! Please enter valid 9 digits phone number', 'woocommerce'), 'error' );
}
// Number starting with "08" with more digits than 10
elseif ( strpos($phone,'08') === 0 && is_numeric($phone) && $length > 10 ) {
wc_add_notice( __('Incorrect Phone Number! Please enter valid 10 digits phone number', 'woocommerce'), 'error' );
}
// Optional: Number not starting with "02" or "08"
elseif ( ! ( strpos($phone,'02') === 0 || strpos($phone,'08') === 0 ) ) {
wc_add_notice( __('Incorrect Phone Number! Phone number must start with "02" or "08"', 'woocommerce'), 'error' );
}
// Optional: Not numerical input
elseif ( ! is_numeric($phone) ) {
wc_add_notice( __('Incorrect Phone Number! Phone number only accept numbers', 'woocommerce'), 'error' );
}
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。