i'm building a google map shortcode plugin and i use wp_localize_script to pass variables to js script like (lat , lng , zoom...) . but i have an issue : when i use this shortcode twice or more in a page , just the first one that works .

i know that to solve my issue i should generate a script for each shortcode with unique variable names etc..

does anyone know how this can be accomplished??

  • edit your question to explain what does'nt work and the resultat of the debug you have done. – mmm Jan 13 '18 at 12:26
  • wp_localize_script only works once for each handle. You might want to look to create a new instance for each shortcode or mabye use html data passing through attributes like this <div data-lat="<?php echo $latitude; ?>"></div> – Wilco Jan 13 '18 at 19:19
  • Possible duplicate of wordpress.stackexchange.com/questions/135821/… – Wilco Jan 13 '18 at 19:22
  • @Wilco and what if we use wp_localize_script each time with different or unique handle ? – geeky87 Jan 13 '18 at 20:27
  • @Wilco and I don't really understand the logic behind using data attribute for this issue . – geeky87 Jan 13 '18 at 20:28

I would do the following:

  • Shortcodes to have unique names passed to them.
  • According to that name to build div with a unique id and a js function with a unique name.
  • Load google script at the end of template(in which there is likelihood to have google maps).
  • Run the function to display the map when it is scrolled in view.

Not gonna go into how to to pass attributes to shortcode but the code should look something like this:

function map_shortcode($atts){
    //deal with $atts
    <div id="map-<?php echo $unique_name ?>"></div>
    function mapInit<?php echo $unique_name ?>() {
                var fenway = {lat: <?php echo $lat; ?>,
                lng: <?php echo $lng; ?>};

                var map = new google.maps.Map(document.getElementById('map-<?php echo $unique_name ?>'), {
                    center: fenway,
                    zoom: <?php echo $zoom; ?>
    $(document).ready(function( $ ) {
    functionWhenUserScrollsToMap(){ // I hope you can figure it out how to implement this
        mapInit<?php echo $unique_name ?>();
    } );

The important thing is:

  • You only load once the google map script.
  • Each map canvas should have unique id.
  • Each map js function should have unique name.
  • After the maps script has loaded you can call the functions.
  • The document ready function and after the scroll should be sufficient for this.
  • You may need to not load the google script asyncronously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.