-
-
Save dgoze/dfe19f64532835e01fea1c42cfa58482 to your computer and use it in GitHub Desktop.
Generate a phone link with an aria-label for accessibility.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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