"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.
Opens WPIDE on
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
- 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.