Click-to-Load Google Maps Embeds
Replaces embedded Google Maps in your content with a placeholder that loads the map only when clicked, for faster pages and fewer third-party cookies.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === strpos( $content, 'google.com/maps' ) || is_feed() ) {
return $content;
}
$count = 0;
$content = preg_replace_callback( '#<iframe[^>]+src=(["\'])(https://www\.google\.com/maps/embed[^"\']*)\1[^>]*>\s*</iframe>#i', function ( $m ) {
$width = preg_match( '/width=["\']?(\d+)/', $m[0], $w ) ? (int) $w[1] : 4;
$height = preg_match( '/height=["\']?(\d+)/', $m[0], $h ) ? (int) $h[1] : 3;
return sprintf(
'<div class="wpide-map" data-src="%1$s" style="position:relative;aspect-ratio:%2$d/%3$d;max-width:100%%;background:#e8eaed;display:flex;align-items:center;justify-content:center"><button type="button" class="wp-element-button">Show map</button></div>',
esc_attr( html_entity_decode( $m[2], ENT_QUOTES ) ),
max( 1, $width ),
max( 1, $height )
);
}, $content, -1, $count );
if ( $count ) {
$GLOBALS['wpide_lazy_maps_used'] = true;
}
return $content;
}, 20 );
add_action( 'wp_footer', function () {
if ( empty( $GLOBALS['wpide_lazy_maps_used'] ) ) {
return;
}
?>
<script>
document.addEventListener( 'click', function ( event ) {
var box = event.target.closest( '.wpide-map' );
if ( ! box || 0 !== box.dataset.src.indexOf( 'https://www.google.com/maps/embed' ) ) {
return;
}
var frame = document.createElement( 'iframe' );
frame.src = box.dataset.src;
frame.loading = 'lazy';
frame.referrerPolicy = 'no-referrer-when-downgrade';
frame.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;border:0';
box.innerHTML = '';
box.appendChild( frame );
} );
</script>
<?php
} );
Notes
Only maps pasted as embed iframes in post content are replaced.
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.