ACF and the Google maps API error

If you use Google Maps on your websites, chances are you’ve come across errors regarding the new API key.

This is a bit of a pain, as you need to register each new domain. Luckily, it’s not too tricky.

I’ll outline the steps below.

Getting your API key

First, you’ll need to generate your API key from Google.

  • Go to¬†https://developers.google.com/maps/documentation/javascript/get-api-key and click on ‘Get a key’
  • Enter your project name
  • Create your API
  • On the ‘Your all set’ screen, click the ‘Go to console’ link
  • Click on ‘Credentials’ in the left-hand menu
  • Click ‘Create credentials’ and then select API key
  • Next, select ‘Browser key’
  • Give these credentials a name – for example, the name of your website
  • Enter any domains that you would like to use with this key (for example you might want to add local, staging and production domains here)
  • Click ‘Create’, copy the key that is generated, and paste it somewhere that you can refer back to

Adding your key to ACF

Now you’ll need to tell ACF your Google API key.

Add the following to your functions.php, or other function or plugin file (replacing ‘xxx’ with your API key):

For ACF

function my_acf_google_map_api( $api ){
	
	$api['key'] = 'xxx';
	
	return $api;
	
}

add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');

For ACF Pro

function my_acf_init() {
	
	acf_update_setting('google_api_key', 'xxx');
}

add_action('acf/init', 'my_acf_init');

That’s the back-end done, and Google Maps should now display correctly on your admin screens. Now for the front-end.

Fixing the front-end

The next step is to fix the maps being output in the front end. This is a bit more straightforward (at least is was in our case).

Where you reference the Google API script, simply add your new API Key to the end of the URL like so:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

You can also do this using wp_enqueue_script or wp_register_script, by using

https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY

as the URL parameter.

Please let us know if you found that useful, or if you have any improvements to the process, by emailing us at hello@highrise.digital.

Highrise Digital | A WordPress agency built for business

About the author

Co-founder and lead front-end developer at Highrise Digital. Keith has a passion for building beautiful, fast and usable websites.