Quick and Simple Telephone Function

Nearly every site I build outputs a phone number somewhere. The header, the footer, the sidebar, sometimes more places. This is a just a simple function that I wrote to make it a little bit easier. The function accepts two parameters; the phone number and a boolean which determines output style.

Typically, I will add an input in either customizer or the theme options page. This way the website admin can modify the phone number at will. There are many ways that sites want to display phone numbers but there is usually some non-numeric indicator of the area code, local exchange and number (i.e. (555) 123-4567, 555.123.4567, etc).

We take that number and make it into our html. <a href=“tel:5551234567”>(555) 123-4567</a>. The function below just uses a simple regex to remove anything that’s not a number and either returns the number of the full anchor tag.

function aad_clean_phone( $number_to_clean, $return_type = false ) {
$clean = preg_replace( \'/\\D/\', "", $number_to_clean );
	if ( $return_type ) :
		return '< a href="tel:' . $clean . '">' . $number_to_clean . '';
	else :
           return $clean;
endif;
}

Example Uses and Outputs

We’ll assume our input is (555) 123-4567
<?php echo aad_clean_phone( get_theme_mod('phone'), false ); ?>

HTML Output: 5551234567

<?php echo aad_clean_phone( get_theme_mod('phone'), true ); ?>

// Same thing, as $return_value is set to true by default
<?php echo aad_clean_phone( get_theme_mod('phone') ); ?>

HTML Output: <a href=”tel:5551234567″>(555) 123-4567</a>

Check out the Gist on GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.