Add google maps to a page in wordpress

One can find a good description of how to implement google maps into a html page on google. But how can we implement a map in wordpress?

First we need a latitude and a longitude for our desired place which we can get from here or elsewhere:

Then we need a google api key. If you do not have one already, here is how you can get it:

Now we can add a page, let’s say a contact page in our wordpress backend where we add a div with the id ‚map‘. In our style.css we can set a width, a height and a background-color for the map div.

With that done we need to add a map.js file e.g. in an assets folder in our theme or plugin. Here we can insert the initMap function described on google where we replace the lat and long with our data.

And finally we need to enqueue the map.js file and the external google api which can be achieved by using ‚wp_enqueue_script‚ like so:

The first statement ensures that the google maps functionality is only loaded on the contact page. For more info check WordPress Conditional Tags. Then two times ‚wp_enqueue_script‚ and finally the ‚add_filter‚ function with the ‚script_loader_tag‚ parameter adds the async and defer tags to the script tag.

This goes into the functions.php of our theme or to any appropriate place in our plugin. And that’s it.