Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.