I am trying for format the provided phone number to "920001234567" format just at the moment when customer click on submit button. I want the phone number to get stored in database with this format. Here is the code I am trying to use. What's wrong in it?
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;
}
Try the following as your code is not really saving anything in database as returning the formatted value, is not the right way in an action hook.
The woocommerce_checkout_create_order
action hook is a really better alternative to woocommerce_checkout_update_order_meta
hook…
I have reuse your formatting code in the following hooked function:
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 );
}
}
Code goes in function.php file of your active child theme (or active theme). tested and work.