Alicia Ramirez

Advanced Custom Fields Google Maps Tutorial

Update (Oct. 31, 2016): Google Maps now requires that you have an API Key in order to add maps via ACF. The tutorial reflects this new requirement.

One of my go-to plugins is Advanced Custom Fields. It is versatile, and makes adding custom fields to posts, pages, custom post types, and even user profiles a breeze. Unfortunately, their documentation is sometimes not very beginner friendly (I’ve written about this in the past), so today I’ll try to help out those trying to use the Google Map custom field.

Unlike some of their other custom fields, which allow you to simply use <?php the_field('field_name'); ?> to output the content of the field for that particular post or page, this particular field, requires quite a bit of extra code. It’s all listed in their code example; I will simply explain step by step where to put in that code.

Step 0

Before you can use Google Maps you need to get a Google Map API Key. You can use the Standard API (it allows 25,000 map views  per day), or if you have a lot of traffic, you’ll need to set up the Premium Plan.

Step 1

Paste this code into your stylesheet (style.css), wherever you think is appropriate:

 Step 2

Create a new file, and copy-paste the following code in it:

Save that file in your theme folder, and name it google-maps.js or something similar. In my theme, all scripts are in the library/js folder.

Step 3

Now you need to add the scripts to your template. You can paste the link in the header of your template, but that’s not a very good practice; it’s much better to add them via wp_enqueue_script() .

In your functions.php file, add the following code:

On lines 2 and 10, replace “XXXX” for your Google Map API Key.

On line 3, make sure that the path to the script points to where you saved the file in step 2.

Step 3 – optional

If you only want to load your map in certain page, for example, the “Contact” page, you can modify the code above like this:

This way, the scripts won’t be loaded in other pages, where they are not necessary.

Step 4

On the template where you want to add the map, add the following code inside the loop:

Make sure that you change the name ‘location‘ in get_field('location'); to match the name of your custom field.

That’s it. Your map should be showing, along with the location selected.

Exit mobile version