Skip to content

Instantly share code, notes, and snippets.

@lori
Last active August 2, 2017 11:26
Show Gist options
  • Save lori/3d9f3dd61e63d20f1da337a1d3885af5 to your computer and use it in GitHub Desktop.
Save lori/3d9f3dd61e63d20f1da337a1d3885af5 to your computer and use it in GitHub Desktop.
Adds a google map to a post using coordinates from custom fields
<?php
/**
* Google maps shortcode
*
* Adds a google map to a post using coordinates from custom fields
*
* @return string HTML to show a Google map
*/
function bd_map_sc($atts) {
global $post;
$post_id = $post->ID;
$location = get_post_meta($post_id, 'your-custom-field-name', true);
$lat = $location['lat'];
$lng = $location['lng'];
$map = '<style>
#map {
height: 400px;
width: 100%;
}
</style>
<div id="map"></div>
<script>
function initMap() {
var map_coords = {lat: ' . $lat . ', lng: ' . $lng . '};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 14,
center: map_coords
});
var marker = new google.maps.Marker({
position: map_coords,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=ADD-YOUR-GOOGLE-MAPS-API-KEY-HERE&callback=initMap">
</script>';
return $map;
}
add_shortcode('bd_map', 'bd_map_sc');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment