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
- Replace
YOUR_API_KEY
with an actual Google Maps API key
- Get an API key from Google Cloud Console
- Enable "Maps Embed API" in Google Cloud Console
Plugin Solutions
If you prefer using a plugin, here are reliable options:
-
Maps Widget for Google Maps - Lightweight plugin for simple map embeds
-
WP Google Maps - Feature-rich mapping solution
-
Advanced Google Maps - Customizable map styling options
Security Considerations
- Always validate and sanitize address inputs
- Keep your API key secure
- 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.