Embed a Map From an ACF Google Map Field
Adds an [acf_map name="location"] shortcode that shows a lazy-loaded embedded map and a directions link for the place saved in an ACF Google Map field.
Opens WPIDE on
Code
add_shortcode( 'acf_map', function ( $atts ) {
$atts = shortcode_atts( array( 'name' => 'location', 'zoom' => 15, 'height' => 360, 'post_id' => 0 ), $atts, 'acf_map' );
$post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();
if ( ! $post_id || ! function_exists( 'get_field' ) || ! is_post_publicly_viewable( $post_id ) ) {
return '';
}
$map = get_field( sanitize_key( $atts['name'] ), $post_id );
if ( ! is_array( $map ) || ! isset( $map['lat'], $map['lng'] ) ) {
return '';
}
$coords = (float) $map['lat'] . ',' . (float) $map['lng'];
$label = ! empty( $map['address'] ) ? $map['address'] : $coords;
$src = add_query_arg( array( 'q' => $coords, 'z' => min( 21, absint( $atts['zoom'] ) ), 'output' => 'embed' ), 'https://maps.google.com/maps' );
$dir = add_query_arg( array( 'api' => 1, 'destination' => $coords ), 'https://www.google.com/maps/dir/' );
return '<div class="acf-map-embed"><iframe src="' . esc_url( $src ) . '" title="' . esc_attr( 'Map: ' . $label ) . '" loading="lazy" referrerpolicy="no-referrer-when-downgrade" style="width:100%;height:' . absint( $atts['height'] ) . 'px;border:0"></iframe>'
. '<p><a href="' . esc_url( $dir ) . '" target="_blank" rel="noopener">Get directions</a> — ' . esc_html( $label ) . '</p></div>';
} );
Notes
The embed needs no API key. Change height="..." to resize; the map always fits the screen width.
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.