0

I am looking to implement this code on my wordpress site as efficiently as possible

https://developers.google.com/maps/documentation/javascript/styling

and I only want the JS to load on posts/pages that I will be using the map. Can't figure out how to start with this!

EDIT:

What if I use the enqueue part inside the function ? Is this a good construct?

function x_shortcode_google_map( $atts, $content = null ) {
  extract( shortcode_atts( array(
    'id'           => '',
    'class'        => '',
    'style'        => '',
    'lat'          => '',
    'lng'          => '',
    'drag'         => '',
    'zoom'         => '',
    'zoom_control' => '',
    'height'       => '',
    'hue'          => '',
    'no_container' => '',
    'api_key'      => ''
  ), $atts, 'x_google_map' ) );

  static $count = 0; $count++;

  $id           = ( $id           != ''     ) ? $id : 'x-google-map-' . $count;
  $class        = ( $class        != ''     ) ? 'x-map x-google-map ' . esc_attr( $class ) : 'x-map x-google-map';
  $style        = ( $style        != ''     ) ? 'style="' . $style . '"' : '';
  $height       = ( $height       != ''     ) ? 'style="padding-bottom: ' . $height . ';"' : '';
  $no_container = ( $no_container == 'true' ) ? '' : ' with-container';

  $js_params = array(
    'lat'         => ( $lat          != ''     ) ? $lat : '40.7056308',
    'lng'         => ( $lng          != ''     ) ? $lng : '-73.9780035',
    'drag'        => ( $drag         == 'true' ),
    'zoom'        => ( $zoom         != ''     ) ? $zoom : '12',
    'zoomControl' => ( $zoom_control == 'true' ),
    'hue'         => ( $hue          != ''     ) ? $hue : '',
  );

  $data = cs_generate_data_attributes( 'google_map', $js_params );

  $script_url = 'https://maps.googleapis.com/maps/api/js';

  if ( $api_key ) {
    $api_key = esc_attr( $api_key );
    $script_url = add_query_arg( array( 'key' => $api_key ), $script_url );
  }

  wp_register_script( 'cs-google-maps', $script_url );
  wp_enqueue_script( 'cs-google-maps' );

  $output = "<div id=\"{$id}\" class=\"{$class}{$no_container}\" {$data} {$style}><div class=\"x-map-inner x-google-map-inner\" {$height}></div>" . do_shortcode( $content ) . "</div>";

  return $output;
}

add_shortcode( 'x_google_map', 'x_shortcode_google_map' );
2
  • I'm not entirely sure you'll be able to focus in on whether the page has the code or not, but you could use wp_enqueue_scripts with a condition as seen in this question. Commented Aug 19, 2016 at 19:23
  • If you have additional information or questions that pertains to your original questions, please click the "Edit" button above and add in that information. The Answer section ( below ) is specifically for answers. Commented Aug 19, 2016 at 20:44

2 Answers 2

0

First of all enqueue the Google Maps API js in the right way. look for a function which is hooked on wp_enqueue_scripts and wp_enqueue_script() to enqueue Google Maps API

function wp_mk_scripts() {
    if ( is_singular() ) {
        wp_enqueue_script( 'wp-mk-maps-js', 'https://maps.googleapis.com/maps/api/js', array( 'jquery' ), null, true );
        wp_enqueue_script( 'wp-mk-gmaps-function', get_stylesheet_directory_uri() . '/js/maps.js', array( 'jquery' ), null, true );
    }
}
add_action( 'wp_enqueue_scripts', 'wp_mk_scripts' );

then in your theme_folder/js/maps.js paste the map code between <script></script> tags in Style Google Maps

Now call the <div id="map"></div> div anywhere in the template to display the map.

2
  • yes but this loads the script everywhere.. What if I create a shortcode and put the script there like my answer below ? Commented Aug 19, 2016 at 19:34
  • wrap the wp_enqueue_script() function in if ( is_singular() ) {} to load the script only on posts and pages. i have updated the answer above. Commented Aug 19, 2016 at 19:38
0

Your approach is close to being correct, but enqueuing scripts within the shortcode function is not the best practice because WordPress loads scripts in the footer or header, and doing it this way may not ensure proper execution.

Best Practice Approach Instead of enqueuing inside the shortcode, use wp_enqueue_scripts and load the script conditionally only when the shortcode is used.


Optimized Implementation

function x_shortcode_google_map( $atts, $content = null ) {
    extract( shortcode_atts( array(
        'id'           => '',
        'class'        => '',
        'style'        => '',
        'lat'          => '',
        'lng'          => '',
        'drag'         => '',
        'zoom'         => '',
        'zoom_control' => '',
        'height'       => '',
        'hue'          => '',
        'no_container' => '',
        'api_key'      => ''
    ), $atts, 'x_google_map' ) );

    static $count = 0; $count++;

    $id           = ( $id != '' ) ? $id : 'x-google-map-' . $count;
    $class        = ( $class != '' ) ? 'x-map x-google-map ' . esc_attr( $class ) : 'x-map x-google-map';
    $style        = ( $style != '' ) ? 'style="' . esc_attr( $style ) . '"' : '';
    $height       = ( $height != '' ) ? 'style="padding-bottom: ' . esc_attr( $height ) . ';"' : '';
    $no_container = ( $no_container == 'true' ) ? '' : ' with-container';

    $js_params = array(
        'lat'         => ( $lat != '' ) ? esc_attr( $lat ) : '40.7056308',
        'lng'         => ( $lng != '' ) ? esc_attr( $lng ) : '-73.9780035',
        'drag'        => ( $drag == 'true' ),
        'zoom'        => ( $zoom != '' ) ? esc_attr( $zoom ) : '12',
        'zoomControl' => ( $zoom_control == 'true' ),
        'hue'         => ( $hue != '' ) ? esc_attr( $hue ) : '',
    );

    $data = cs_generate_data_attributes( 'google_map', $js_params );

    // Store API key in a global variable for use in enqueue function
    global $google_maps_api_key;
    $google_maps_api_key = $api_key;

    // Trigger script loading
    add_action( 'wp_enqueue_scripts', 'enqueue_google_maps_script' );

    $output = "<div id=\"{$id}\" class=\"{$class}{$no_container}\" {$data} {$style}><div class=\"x-map-inner x-google-map-inner\" {$height}></div>" . do_shortcode( $content ) . "</div>";

    return $output;
}

add_shortcode( 'x_google_map', 'x_shortcode_google_map' );

function enqueue_google_maps_script() {
    global $google_maps_api_key;

    if ( ! wp_script_is( 'cs-google-maps', 'enqueued' ) ) {
        $script_url = 'https://maps.googleapis.com/maps/api/js';

        if ( ! empty( $google_maps_api_key ) ) {
            $script_url = add_query_arg( array( 'key' => esc_attr( $google_maps_api_key ) ), $script_url );
        }

        wp_register_script( 'cs-google-maps', $script_url, array(), null, true );
        wp_enqueue_script( 'cs-google-maps' );
    }
}

Why This Is Better

  1. Scripts Load Properly

    • The Google Maps API is enqueued only when the shortcode is used on a page/post.
    • Scripts load in the footer (true argument in wp_register_script), improving performance.
  2. No Conflicts

    • Avoids issues with multiple shortcodes trying to enqueue the same script.
    • Ensures the API key is used consistently.
  3. More Efficient

    • wp_enqueue_scripts is hooked only when the shortcode is used.
    • If a page doesn't use the shortcode, Google Maps script won’t be loaded.

Final Steps

  • Add [x_google_map lat="40.712776" lng="-74.005974" zoom="10" api_key="YOUR_GOOGLE_MAPS_API_KEY"][/x_google_map] to your post/page to test.

Would you like to add custom styles for the Google Map as well? You can enqueue a separate JavaScript file to handle map styles dynamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.