使用wp_enqueue_script加载Google Maps API

时间:2012-02-29 17:53:01

标签: wordpress google-maps

我正在尝试使用以下语法在WordPress管理类中加载Google Maps API:

add_action('admin_enqueue_scripts', array(&$this, '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正在逃避“&”到“&#038”。这实际上使Google服务器拒绝了该请求。当我直接在浏览器地址栏中输入“& sensor = false”时,它会正常加载。

我在WordPress trac系统中看到了这种类型的错误:http://core.trac.wordpress.org/ticket/9243但它被视为无效,并且响应请求的管理员以某种方式显示“&#038”方法没问题。从谷歌的角度来看,这绝对不是好事。

我当然可以获得将HTML作为脚本标记回显的函数,但如果可能的话,我宁愿使用wp_enqueue_script系统。

任何人都知道解决方案吗?

干杯,

RAFF

1 个答案:

答案 0 :(得分:7)

我的代码中有类似的东西,它工作正常(甚至编码为&#038)。我怀疑你的问题是它是双重编码的,因为你已经有&。尝试将其更改为:

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

对于它的价值,我们的(工作)代码是:

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设置为hl=en

修改

看起来在最新版本的WordPress中行为发生了变化 - 上面的内容不起作用(但是我会将它留给旧版本的人)。我能看到回应脚本的唯一选择是添加clean_url过滤器,如下所示:

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;
}

非常难看,但可能比回复脚本要好一点,因为它仍然会使用WordPress依赖管理。