admin管理员组

文章数量:1336644

I am trying to display a google map using short code for a plugin I am building, but I can not get it to work. Does anyone have some advice on this? Here is my code:

add_shortcode( 'show_map', array('hotSpot', 'create_map'));
function create_map() {
?>
<script src=""></script>
<script>
  function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(34.040819,-84.604660),
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

<?php 
return '<div id="map_canvas"></div>';    
}

I am trying to display a google map using short code for a plugin I am building, but I can not get it to work. Does anyone have some advice on this? Here is my code:

add_shortcode( 'show_map', array('hotSpot', 'create_map'));
function create_map() {
?>
<script src="https://maps.googleapis/maps/api/js"></script>
<script>
  function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(34.040819,-84.604660),
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

<?php 
return '<div id="map_canvas"></div>';    
}
Share Improve this question asked Aug 14, 2014 at 18:00 ZachZach 531 silver badge3 bronze badges 2
  • Is this code inside a class? – sakibmoon Commented Aug 14, 2014 at 18:24
  • The shortcode function should only return a string and not directly output anything. Your <script> elements are being directly outputted and would be emitted before the_content() output since the_content() buffers its output as it does filter processing (including shortcode processing) This is probably not the cause of your problem but it is not how WordPress intended for shortcodes to produce their output. – user27457 Commented Aug 14, 2014 at 21:40
Add a comment  | 

1 Answer 1

Reset to default 1

Based on what I can see, it looks like your calling the create_map function incorrectly.

add_shortcode() takes 2 parameters, the name of the shortcode and the function that gets rendered when called.

The array you are passing is how to call a method inside of a class. You're basically saying call the create_map method from the hotSpot class.

Assuming this code is not inside the hotSpot class - try this:

//change
add_shortcode( 'show_map', array('hotSpot', 'create_map'));

//to 
add_shortcode( 'show_map','create_map');

Hope this helps!

本文标签: shortcodeExecuting Javascript in Plugin