// Add country calling code prefix in woocommerce billing phone
add_action( 'wp_footer', 'wpsh_add_callback' );
function wpsh_add_callback(){
?>
<script type="text/javascript">
( function( $ ) {
$( document.body ).on( 'updated_checkout', function(data) {
var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>",
country_code = $('#billing_country').val();
var ajax_data = {
action: 'append_country_prefix_in_billing_phone',
country_code: country_code
};
$.post( ajax_url, ajax_data, function( response ) {
$('#billing_phone').val(response);
});
} );
} )( jQuery );
</script>
<?php
}
add_action( 'wp_ajax_nopriv_append_country_prefix_in_billing_phone', 'wpsh_add_phone_prefix' );
add_action( 'wp_ajax_append_country_prefix_in_billing_phone', 'wpsh_add_phone_prefix' );
function wpsh_add_phone_prefix() {
$calling_code = '';
$country_code = isset( $_POST['country_code'] ) ? sanitize_text_field( $_POST['country_code'] ) : '';
if( $country_code ){
$calling_code = WC()->countries->get_country_calling_code( $country_code );
$calling_code = is_array( $calling_code ) ? $calling_code[0] : $calling_code;
}
echo $calling_code;
die();
}
// Phone number shoud be at least 6 digits long. This avoids the problem with not adding a phone number
add_action('woocommerce_checkout_process', 'wpsh_validate_phone');
function wpsh_validate_phone() {
if (isset($_POST['billing_phone'])) {
$phone = strlen(preg_replace('/[^0-9]/', '', $_POST['billing_phone']));
if ($phone < 6) {
wc_add_notice( __( '<strong>Billing Phone</strong> must be at least 6 digits long.' ), 'error' );
}
}
}