Shortcode callback for add_action(‘wp_footer’)

I am trying to build a Google Maps shortcode using the gMap plugin from Github, not a plain iframe. For which I have to echo a custom inline script for EACH shortcode, right before the closing body tag, after jQuery and all other scripts have been loaded.

The following shortcode works, but it only adds the inline script once, not for every shortcode. When I add three [map] shortcodes, it should add the inline script for each og the shortcodes, three inline scripts, to the footer. But it only adds one script. Which is the one from the last shortcode.

Read More
class map_class
{
    protected static $var = '';

    public static function map_callback($atts) 
    {     
        extract(shortcode_atts(array(
                'address'               => 'Main Street, New York City, United States',
                'zoom'                      => '14'
            ), $atts));

            $id= rand();

            $script  = '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>';
            $script .= '<script type="text/javascript">
                                        jQuery(document).ready(function(){
                                            jQuery("#googlemap' . $id . '").gMap({
                                                address: "' . $address . '",
                                                zoom: ' . $zoom . '
                                            });
                                        });
                                    </script>';

        self::$var = $script;

        add_action( 'wp_footer', array ( __CLASS__, 'footer' ), 20 );

                return '<div id="googlemap' . $id . '" class="googlemap" style="height: ' . $height . '"></div>';           
    }

    public static function footer() 
    {
      echo self::$var;
    }

}
add_shortcode( 'map', array ( 'map_class', 'map_callback' ) );

$script is holding all three inline scripts, but when I try to call $script in add_action like this:

add_action( 'wp_footer', array ( __CLASS__, $script ), 20 );

.. I get the following error:

“First argument is expected to be a valid callback”

I appreciate any help here.

Related posts

1 comment

  1. each time you call the shortcode function, you overwrite the previous script var with the current version. make it an array instead of a string:

    self::$var[] = $script;
    

    and then output with foreach:

    public static function footer() 
    {
        foreach( self::$var as $script ){
            echo $script;
        }
    }
    

Comments are closed.