Halloween Sale 15% off Ends in See the plans
PHP

"Get Directions" Map Link Shortcode

Adds a [map_link] shortcode that links an address to Google Maps or Apple Maps directions, opening the visitor's maps app on phones, without embedding a map or loading any script.

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

Code

// Default address used when the shortcode has none.
$wpide_map_address = '';

add_action( 'init', function () use ( $wpide_map_address ) {
    add_shortcode( 'map_link', function ( $atts ) use ( $wpide_map_address ) {
        $atts    = shortcode_atts( array( 'address' => $wpide_map_address, 'text' => '', 'app' => 'google' ), $atts, 'map_link' );
        $address = trim( sanitize_text_field( $atts['address'] ) );
        if ( '' === $address ) {
            return '';
        }

        $url = 'apple' === $atts['app']
            ? 'https://maps.apple.com/?daddr=' . rawurlencode( $address )
            : 'https://www.google.com/maps/dir/?api=1&destination=' . rawurlencode( $address );

        return sprintf(
            '<a class="wpide-map-link" href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> (opens in a new tab)</span></a>',
            esc_url( $url ),
            esc_html( '' !== $atts['text'] ? $atts['text'] : $address )
        );
    } );
} );

Notes

Example [map_link address="10 Downing St, London" text="Get directions"]; add app="apple" for Apple Maps links.

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.