Skip to content

Instantly share code, notes, and snippets.

@dgoze
Created July 24, 2024 18:05
Show Gist options
  • Save dgoze/b257d4eedd76de53ef8947c9a9e36ad2 to your computer and use it in GitHub Desktop.
Save dgoze/b257d4eedd76de53ef8947c9a9e36ad2 to your computer and use it in GitHub Desktop.

Three options to format US phone numbers

PHP
Using PHP to extract (substr) the phone number into separate parts, inject the separator and reassemble. Output with a shortcode

Loops and Logic
Use Loops and Logic's regex feature using capture groups to extract the parts, then insert separator when reassembling the capture groups before outputting the phone number.

Javascript
If you don't have control over the HTML, you can use JS to extract (slice) the phone number into separate parts, inject the separator and reassemble.

<?php
if (function_exists('get_field')) {
add_shortcode('formatted_us_phone', function ($atts) {
$atts = shortcode_atts(array(
'separator' => '.', // Defaults to . but you could do a dash, space, etc
), $atts);
$phone_number = get_field('phone_number'); // Your ACF field here
if ($phone_number) {
$length = strlen($phone_number);
if ($length == 10) {
// Format 10-digit phone number
$formatted_phone = substr($phone_number, 0, 3) . $atts['separator'] .
substr($phone_number, 3, 3) . $atts['separator'] .
substr($phone_number, 6, 4);
} elseif ($length == 11) {
// Format 11-digit phone number
$formatted_phone = substr($phone_number, 0, 1) . $atts['separator'] .
substr($phone_number, 1, 3) . $atts['separator'] .
substr($phone_number, 4, 3) . $atts['separator'] .
substr($phone_number, 7, 4);
} else {
// Return the original phone number if it doesn't match the expected lengths
return $phone_number;
}
return $formatted_phone;
}
return '';
});
}
<!-- Format phone number with L&L regex -->
<Format replace_pattern="/(\d{3})(\d{3})(\d{4})/" with="$1.$2.$3"><Field phone_number /></Format>
<!-- An example of this in use -->
<a href="tel:{Field phone_number /}{If field=phone_extension};{Field phone_extension /}{/If}">
<span class="phone-number"><Format replace_pattern="/(\d{3})(\d{3})(\d{4})/" with="$1.$2.$3"><Field phone_number /></Format></span>
<If field="phone_extension">
<span class="phone-extension">ext.<Field phone_extension /></span>
</If>
</a>
jQuery(document).ready(function($) {
// Find all elements with class "phone-number"
$('.phone-number').each(function() {
// Get the phone number from the element
var phoneNumber = $(this).text().trim();
// Format the phone number
var formattedPhoneNumber = phoneNumber.slice(0, 3) + '.' + phoneNumber.slice(3, 6) + '.' + phoneNumber.slice(6);
// Update the content of the element with the formatted phone number
$(this).text(formattedPhoneNumber);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment