【问题标题】:Enqueue Google Maps javascript API with shortcode into Wordpress将带有简码的 Google Maps javascript API 排入 Wordpress
【发布时间】:2015-11-19 06:29:10
【问题描述】:

我花了无数个小时试图弄清楚这一点。我不明白我做错了什么。

我的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');
    }
}

当我将[custom-map-shortcode] 放入页面正文时,地图不会加载。 [custom-map-shortcode] 也没有出现,所以我知道有些事情做对了。但是缺少一些东西。现在我知道我的谷歌地图有效,它已经过测试。 javascript代码没有错。源显示在我的页面源中,当我单击它时,它链接到我的map_script.js。 API 密钥也显示在我的页面源中。

您可以通过http://www.tothenationsworldwide.com自行检查

任何帮助将不胜感激!

【问题讨论】:

  • 源代码表明您正在以某种方式将新 HTML 页面加载到现有文档流中 - 对于 iframe 来说很好,在 div 中不太好。它甚至不是有效的 html 被加载...它恰好在 &lt;div id="map"&gt;&lt;/div&gt; 之前
  • 我有点困惑。我删除了 div id=map 因为据我所知,使用简码时不需要它。你在说什么我不太明白的html页面。我在 wordpress 中使用大学主题,在我的页面中,我还在用 [custom-map-shortcode] 等编写脚本......这是正确的方法吗?还是您在我的问题中建议我的代码不正确?或者可能是我的javascript代码?我的 javascript 代码中没有 html。
  • 我修复了代码,使其不在我的页面上包含 html 标签。现在已解决此问题,但我的问题尚未解决。 [custom-map-shortcode] 没有出现在我的页面上,所以我认为我的简码是正确的
  • 我要说的一件事 - 由于包含了如此多的全尺寸高分辨率照片,该页面的加载速度非常慢(至少对我来说是垃圾宽带连接)。您应该生成图像的缩略图并链接到全尺寸的。无论如何,只是一个观察 - 不能提供对 Wordpress 问题的见解 - 永远不要使用它。
  • 感谢您的意见!非常感谢!

标签: javascript php wordpress api google-maps


【解决方案1】:

我感觉这是因为您的&lt;script src=" 行在js? 之后有一个换行符。只有在浏览器中查看源码才能看到:

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

当我查看源代码时,在那之后 html 颜色编码看起来无效,所以我认为这是其中很大一部分。

【讨论】:

  • 我找不到摆脱换行符的方法。我摆脱了它,但完全不记得如何摆脱它。如果我重新输入它,它仍然会在那时中断。有什么建议吗?此外,任何我没有我的 [cutsom-map-shortcode] 的页面,页面加载错误代码:InvalidKeyOrUnauthorizedURLMapError。我已经浏览了谷歌 api 密钥并注册并验证了我的网站。这不可能。
  • 嗯。这是一个奇怪的现象,这是肯定的!我想不出它为什么会这样分裂,以为我对 Wordpress 的了解不是很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2016-06-18
  • 2015-11-12
相关资源
最近更新 更多