Skip to content

Instantly share code, notes, and snippets.

@mustardBees
Last active May 3, 2023 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustardBees/575694d554ac64033f7a2829d4d60da6 to your computer and use it in GitHub Desktop.
Save mustardBees/575694d554ac64033f7a2829d4d60da6 to your computer and use it in GitHub Desktop.
Generate a phone link with an aria-label for accessibility.
<?php
/**
* Generate a phone link with an aria-label for accessibility.
*
* @link https://link.from.pw/3HElEp9
*
* @param string $phone The phone number to format.
* @param string $class Optional. The CSS class name to add to the link.
*
* @return string The formatted telephone link.
*/
function kanuka_accessible_phone_link( $phone, $class = '' ) {
// Rough check for a valid phone number.
if ( ! preg_match( '/^[0-9+\-()\s]+$/', $phone ) ) {
return $phone;
}
// Remove spaces from phone number.
$tel = preg_replace( '/\s+/', '', $phone );
// Remove non-numeric characters except the plus sign and spaces.
$aria_label = preg_replace( '/[^0-9+\s]/', '', $phone );
// Add full stop at the end of each group of characters.
$aria_label = str_replace( ' ', '. ', $aria_label ) . '.';
// Remove all spaces.
$aria_label = str_replace( ' ', '', $aria_label );
// Add a space between each character.
$aria_label = implode( ' ', str_split( $aria_label ) );
// Remove spaces before full stops.
$aria_label = str_replace( ' .', '.', $aria_label );
// Generate the link.
$link = '<a href="tel:' . $tel . '" aria-label="' . $aria_label . '"';
// Add the class attribute if a class name was provided.
if ( ! empty( $class ) ) {
$link .= ' class="' . $class . '"';
}
$link .= '>' . $phone . '</a>';
// Return the link
return $link;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment