Don't know where to look?

You can search all my notes here

Use Google-Maps in WordPress

Since some time Google-Maps started requiring API-keys to work properly. I embed these keys in the following manner:

functions.php
php
<?php
define( 'MAPS_API_KEY', '<Key von Google>' );

add_action('acf/init', function () {
	acf_update_setting('google_api_key', MAPS_API_KEY);
});

This way ACF will use the right key in the backend and all custom PHP-code can rely on the constant MAPS_API_KEY.

If you didn’t install or activate ACF, this code won’t throw any errors since the action “acf/init” will never be called.

If you still need a key:

console.cloud.google.com/google/maps-apis

Embed the Google-Maps Javascript via PHP

functions.php
php
<?php
add_action('wp_enqueue_scripts', function () {
  wp_register_script(
    'google-maps',
    'https://maps.google.com/maps/api/js?' . http_build_query([
      'key' => MAPS_API_KEY
    ]),
    [],
    null,
    true
  );
});

To insert the script into your html, either add google-maps to the dependencies of your main js or use the following code to enqeue the script directly: wp_enqueue_script('google-maps')

If possible, try to only embed this script on pages where google-maps is needed.

Comments

Post-Meta
Included files
  • functions.php
  • readme.md
Download all