在Woocommerce中提交结帐表单时格式化帐单电话号码



我正在尝试将提供的电话号码格式化为"920001234567"格式,就在客户单击提交按钮的那一刻。我希望电话号码以这种格式存储在数据库中。这是我尝试使用的代码。这是怎么回事?

add_action( 'woocommerce_checkout_update_order_meta', 
'formatPhoneOnComplete', 10, 2 );
function formatPhoneOnComplete($order_id) {
$order = wc_get_order($order_id);
$order_data = $order->get_data();
$phone = $order_data['billing']['phone'];
$phone = trim($phone);
$phone = str_replace([' ','-','_'],'',$phone);
if(empty($phone)) {
return NULL;
}
$phone = ltrim(ltrim($phone, '0'),'+');
if(strlen($phone) <= 11) {
$phone = '92' . ltrim($phone,0);
}
return $phone;
}

尝试以下操作,因为您的代码并没有真正将任何内容保存在数据库中,因为返回格式化值,这不是操作钩子中的正确方式。

woocommerce_checkout_create_order动作钩是woocommerce_checkout_update_order_meta钩子的更好替代品......

我在以下挂钩函数中重用了您的格式化代码:

add_action( 'woocommerce_checkout_create_order', 'additional_hidden_checkout_field_save', 20, 2 );
function additional_hidden_checkout_field_save( $order, $data ) {
if( ! isset($data['billing_phone']) ) return;
if( ! empty($data['billing_phone']) ){
$phone = str_replace([' ','-','_'],['','',''], $data['billing_phone']);
$phone = ltrim(ltrim($phone, '0'),'+');
$formatted_phone = strlen($phone) <= 11 ? '92' . ltrim($phone, 0) : $phone;
// Set the formatted billing phone for the order
$order->set_billing_phone( $formatted_phone );
}
}

代码进入函数.php活动子主题(或活动主题(的文件。 经过测试并工作。

最新更新