# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: performance, maps, privacy
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/click-to-load-google-maps/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Click-to-Load Google Maps Embeds" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
