Add a map to your posts

To add a map to your WordPress posts, there are two solutions.

Plugin-free

Let's start by adding a meta box in your "add new post" page. In your theme functions.php file, paste this:

add_action("admin_init", "admin_init");
add_action('save_post', 'save_map');
function admin_init(){
add_meta_box("map-meta", "Map Place", "meta_options", "place", "side", "low");
}
function meta_options(){
global $post;
$custom = get_post_custom($post->ID);
$map = $custom["map"][0];
?>
<label>Map:</label><input type="text" name="map" value="<?php echo $map; ?>" />
<?php
}
function save_map(){
global $post;
update_post_meta($post->ID, "map", $_POST["map"]);
}

Now, in your single.php file, paste this:

<?php
$custom = get_post_custom($post->ID);
$map = $custom["map"][0];
if($map) {
?>
<h4>Map</h4>
<p><a href="http://maps.google.com/maps?q=<?=$map?>&amp;oe=utf-8&amp;client=firefox-a&amp;ie=UTF8&amp;hl=en&amp;hq=<?=$map?>&amp;hnear=&amp;z=14&amp;iwloc=A" title="View on Google Maps" target="_blank"><img src="http://maps.google.com/maps/api/staticmap?center=<?=$map?>&amp;zoom=14&amp;size=440x200&amp;sensor=false&amp;markers=color:red|size=tiny|<?=$map?>" alt="" width="440" height="200" /></a></p>
<?php } ?>

This will create a static map image linked to the Google Maps page. Learn how to customize this code on the Google Static Maps API page.

When writing a post, in the map input box, write your address like this:

Brooklyn+Bridge,New+York,NY

This is a quick and dirty solution, you can also use a plugin !

With a plugin

I use the RomeLuv Google Maps plugin to add a map to my posts. To get started, you need to get a Google Maps API key, it's really simple. After you activate the plugin, choose manual placement with the PHP code. In your theme single.php, add this code wherever you want the map to appear:

<?php if (function_exists(romeluv_single_map)) {
$map = romeluv_single_map('');
if($map) {
echo '<h4>Map</h4>';
}
echo $map;
} ?>

Really simple :)

One comment

  1. diragusa 8 December 2011 at 00:31:50

    but what if you want to use rome luv but want a meta box for it in a form?

Comments are closed.