Click-to-Call Phone Number Shortcode
Adds a [phone_link] shortcode that prints your phone number as a tap-to-call link, formatted for reading but dialled correctly in international format, so it only needs to be changed in one place.
Opens WPIDE on
Code
// Default number, written the way people should read it.
$wpide_phone_number = '+1 (555) 010-0200';
add_action( 'init', function () use ( $wpide_phone_number ) {
add_shortcode( 'phone_link', function ( $atts ) use ( $wpide_phone_number ) {
$atts = shortcode_atts( array( 'number' => $wpide_phone_number, 'text' => '', 'icon' => 'yes' ), $atts, 'phone_link' );
// Drop the "(0)" trunk prefix and everything but digits and a leading plus.
$dial = preg_replace( '/\(0\)/', '', $atts['number'] );
$dial = ( 0 === strpos( trim( $dial ), '+' ) ? '+' : '' ) . preg_replace( '/\D/', '', $dial );
return sprintf(
'<a class="wpide-phone" href="tel:%s">%s%s</a>',
esc_attr( $dial ),
'yes' === $atts['icon'] ? '<span aria-hidden="true">☎ </span>' : '',
esc_html( '' !== $atts['text'] ? $atts['text'] : $atts['number'] )
);
} );
} );
Notes
Set $wpide_phone_number once, then use [phone_link] anywhere; [phone_link number="+44 20 7946 0000" text="Call London"] overrides it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.