Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

wordpress - Loading Google Maps API with wp_enqueue_script

I'm trying to load the Google Maps API using the following syntax:

add_action('admin_enqueue_scripts', 'load_google_maps');

...

function load_google_maps()
{
  // The actual API key is configured in an options page
  $key = get_option('google_maps_api_key');
  $gmaps_url = 'http://maps.googleapis.com/maps/api/js?key=' . $key . '&sensor=false';
  wp_enqueue_script('google-maps', $gmaps_url, NULL, NULL);
}

WordPress is escaping the "&" to "&#038". This actually makes the Google server reject the request. When I type it directly into browser address bar with "&sensor=false" at the end, it loads fine.

I saw a bug of this kind mentioned in the WordPress trac system: http://core.trac.wordpress.org/ticket/9243 but it was dismissed as invalid, and the admin responding to the request showed somehow that the "&#038" approach was fine. It is definitely not fine from Google's point of view.

I could of course just get the function to echo the HTML as a script tag, but I'd rather use the wp_enqueue_script system if possible.

Anyone know of a solution to this?

Cheers,

raff

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've got something similar in our code, and it's working fine (even encoded as &#038). I suspect your problem is that it's being double-encoded, as you already have &. Trying changing it to:

$gmaps_url = 'http://maps.googleapis.com/maps/api/js?key=' . $key . '&sensor=false';

For what it's worth, our (working) code is:

wp_register_script('googlemaps', 'http://maps.googleapis.com/maps/api/js?' . $locale . '&key=' . GOOGLE_MAPS_V3_API_KEY . '&sensor=false', false, '3');
wp_enqueue_script('googlemaps');

($locale in this case is set to hl=en)

Edit

Looks like the behaviour's changed in the latest version of WordPress - the above doesn't work (but I'll leave it for people on legacy versions). The only alternative I can see to echoing the script is to add a clean_url filter, something like this:

add_filter('clean_url', 'so_handle_038', 99, 3);
function so_handle_038($url, $original_url, $_context) {
    if (strstr($url, "googleapis.com") !== false) {
        $url = str_replace("&", "&", $url); // or $url = $original_url
    }

    return $url;
}

Pretty ugly, but perhaps marginally better than echoing the script, as it'll still use the WordPress dependency management.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...