Support

Account

Home Forums ACF PRO Google Maps enqueue scripts

Solving

Google Maps enqueue scripts

  • I am a bit confused with this one:

    I have added:

    // ACF Google Maps: Add API key
    add_filter( 'acf/fields/google_map/api', 'google_maps_api' );
    //Google Maps
    function google_maps_api($apiKey) {
    	$a = 'APIKEY';
    	$apiKey['key'] = $a;
    	return $apiKey;
    }

    It works in admin.

    However in a front-end template according to the docs: https://www.advancedcustomfields.com/resources/google-map/

    I need to load GM js like so:

    <script src=”https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY”></script&gt;

    It works if I do so, but I would be interested in being able to load the Google Maps JS via ACFpro – I mean, when my post_type if the one that contains a Google Map, then ask ACF pro to enqueue the Google Maps JS including my API key that is already set – in the same fashion as it does it in the admin.

    How to tell ACFpro: Now load GoogleMaps js from the template?

  • I use this in one of my in house themes. It simply checks if the current page has a locations field which would require a google map. We then check if google_maps_api function exists in case we forgot to include it. then we enqueue the script to be added in the footer. You can change true to false if you want it in the header.

    add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
    function wpb_adding_scripts() {
        global $post;
        if(!empty(get_field('locations',$post->ID)){
    		if(function_exists('google_maps_api')){
    			$apiKey=google_maps_api();
    			if($apiKey){
    				wp_register_script('googleMapsAPI', 
    					'https://maps.googleapis.com/maps/api/js?key='.$apiKey,
    					'',
    					true
    				);
    				wp_enqueue_script('googleMapsAPI');			
    			}
    		}
        }
    }
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Google Maps enqueue scripts’ is closed to new replies.