Custom code to add a Google Maps embed to a WordPress post

Emily T. Dec 19, 2024 Embedding Google Maps
How can I put a Google Map on my website so visitors can find my location?
What is the best way to programmatically embed a Google Maps iframe in a WordPress post using custom PHP code?
Andy answered Dec 19, 2024

Custom Code Solution

Method 1: Using Functions.php

Add this code to your theme's functions.php file to create a shortcode for embedding Google Maps:

This code creates a [google_map] shortcode with address and zoom parameters:

function custom_google_map_shortcode($atts) {
    $default = array(
        'address' => '1600 Amphitheatre Parkway, Mountain View, CA',
        'zoom' => '14',
        'height' => '450',
        'width' => '100%'
    );
    
    $atts = shortcode_atts($default, $atts);
    
    $address = urlencode($atts['address']);
    
    return sprintf(
        '<iframe 
            width="%s" 
            height="%s" 
            frameborder="0" 
            style="border:0" 
            src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=%s&zoom=%s" 
            allowfullscreen>
        </iframe>',
        $atts['width'],
        $atts['height'],
        $address,
        $atts['zoom']
    );
}
add_shortcode('google_map', 'custom_google_map_shortcode');

Usage in posts/pages:

[google_map address="123 Main St, New York, NY" zoom="15"]

Method 2: Direct PHP Implementation

Add this code directly to your template file where you want the map to appear:

function display_google_map($address = '1600 Amphitheatre Parkway, Mountain View, CA', $zoom = '14') {
    $address = urlencode($address);
    echo '<iframe 
        width="100%" 
        height="450" 
        frameborder="0" 
        style="border:0" 
        src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=' . $address . '&zoom=' . $zoom . '" 
        allowfullscreen>
    </iframe>';
}

// Usage
display_google_map('123 Main St, New York, NY', '15');

Important Notes

  1. Replace YOUR_API_KEY with an actual Google Maps API key
  2. Get an API key from Google Cloud Console
  3. Enable "Maps Embed API" in Google Cloud Console

Plugin Solutions

If you prefer using a plugin, here are reliable options:

  1. Maps Widget for Google Maps - Lightweight plugin for simple map embeds
  2. WP Google Maps - Feature-rich mapping solution
  3. Advanced Google Maps - Customizable map styling options

Security Considerations

  1. Always validate and sanitize address inputs
  2. Keep your API key secure
  3. Set proper HTTP referrer restrictions in Google Cloud Console

The custom code solutions above provide a clean way to embed Google Maps without adding plugin overhead to your site. Choose Method 1 for flexible shortcode usage across posts/pages, or Method 2 for template-specific implementations.