Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 388
codewithfeeling Avatar asked Feb 29 '12 17:02

codewithfeeling


1 Answers

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.

like image 132
Hobo Avatar answered Sep 22 '22 16:09

Hobo