Method 1: Custom Code Solution
Add this code to your theme's functions.php
file or in a site-specific plugin to create a shortcode for embedding Google Maps:
This code creates a [google_map]
shortcode with customizable parameters:
function custom_google_map_shortcode($atts) {
$default = array(
'address' => '123 Main St, New York, NY',
'width' => '100%',
'height' => '400px',
'zoom' => '14'
);
$atts = shortcode_atts($default, $atts);
$map_url = 'https://www.google.com/maps/embed/v1/place';
$api_key = 'YOUR_GOOGLE_MAPS_API_KEY'; // Replace with your API key
$output = sprintf(
'<div class="google-map"><iframe width="%s" height="%s" frameborder="0" style="border:0" src="%s?key=%s&q=%s&zoom=%s" allowfullscreen></iframe></div>',
$atts['width'],
$atts['height'],
$map_url,
$api_key,
urlencode($atts['address']),
$atts['zoom']
);
return $output;
}
add_shortcode('google_map', 'custom_google_map_shortcode');
Add this CSS to your theme's stylesheet or in the WordPress Customizer's Additional CSS section:
.google-map {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
}
.google-map iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Usage example in any post or page:
[google_map address="1600 Amphitheatre Parkway, Mountain View, CA" width="100%" height="400px" zoom="15"]
Method 2: Plugin Solutions
If you prefer using a plugin, here are reliable options:
-
WP Google Maps (https://wordpress.org/plugins/wp-google-maps/)
- Free version includes basic mapping features
- Simple interface for creating and customizing maps
-
Maps Widget for Google Maps (https://wordpress.org/plugins/google-maps-widget/)
- Lightweight plugin
- Easy to use with widgets
Important Notes:
- You'll need a Google Maps API key from the Google Cloud Console
- The custom code solution requires basic knowledge of PHP and WordPress
- Keep your API key secure and restrict it to your domain
- Consider usage limits on the Google Maps API
- Test responsiveness on different screen sizes
The custom code solution offers more control and better performance compared to plugins, but plugins provide an easier setup process and user interface for non-technical users.