简体   繁体   中英

Enqueue Google Maps javascript API with shortcode into Wordpress

I have spent countless hours trying to figure this out. I do not understand what I am doing wrong.

I have this code in my functions.php :

add_shortcode('custom-map-shortcode', 'custom_map_shortcode_callback');

function custom_map_shortcode_callback() {
    return '<div id="map" style="height: 100%; margin: 0;padding: 0;"></div>';
 }

 add_action('wp_enqueue_scripts', 'enqueue_map_script' );
 add_action('wp_head', function(){
     echo '<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&signed_in=true&callback=initMap"></script>';
 });

function enqueue_map_script(){
    global $post;

    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-map-shortcode') ) {
        wp_enqueue_script( 'map-script', get_template_directory_uri() . '/js/map_script.js');
    }
}

When I place [custom-map-shortcode] into the body of my page, the map doesn't load. The [custom-map-shortcode] doesn't show up either, so I know something is doing something right. But something is missing. Now I know my google map works, its been tested. The javascript code is not wrong. The source shows up in my page source and when I click it, it is linked to my map_script.js . The API Key shows up in my page source too.

You can check for yourself at http://www.tothenationsworldwide.com

Any help would be greatly appreciated!

I have a feeling it is because your <script src=" line has a line break in it after the js? . You can only see it when you view source in the browser:

add_action('wp_head', function(){
     // Here you have an invisible line break. Look at your code,
     // you will see your key=...etc is on a new line. That may invalidate it
     //---------------------------------------------------------v
     echo '<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&signed_in=true&callback=initMap"></script>';
 });

When I view the source, html color-coding looks invalid after that point, so I think that is a big part of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM