WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've got shortcode that needs to include JS library only once and only there where it's used.

function shortcode_function($atts, $content = null) {
    $class = shortcode_atts( array('something' => '0'), $atts );

    return "<script src=\"http://maps.googleapis.com/maps/api/js?sensor=false\"></script> 
            And here goes HTML code for the map.";
add_shortcode("sh", "shortcode_function");

The problem is that above example is going to include library several times if maps shortcode is used several times. How can I prevent that? Or more precisely: how can I do it "the correct way"? Can I use wp_enqueue_script() in that place?

Just one requirement: I really need this to include that library only-when-shortcode-is-used.

share|improve this question
up vote 4 down vote accepted

Yes, you should use wp_enqueue_script(). The script will be loaded in the footer (action: wp_footer()). Just once.

To inspect the order of available hooks, functions etc. per request try my plugin T5 WP Load Order.

share|improve this answer
So, add_shortcode is aware of this and it's not too early or too late to register and enqueue this? – Paul Nov 14 '12 at 18:23
The shortcode itself is “script agnostic”. :) You can enqueue scripts any time before wp_footer() was called, be it in a shortcode or somewhere else. Example. – toscho Nov 14 '12 at 18:27
Thanks for that link. It mentions EXACT code that I'm looking for :) It looks like it has been introduced in WP3.3, so just a few months ago. It's hard to tell when it's not too late to run something in WP and when it's already too late (like all these hooks) - I haven't found any debugging method for that, yet, so that's why I asked if it's surely "the correct" way to do it. Thanks! – Paul Nov 14 '12 at 19:34
@Paul See my update for a plugin to inspect the load order. – toscho Nov 14 '12 at 19:36
Thanks :) I will surely try this. It's hard to get to know what WordPress actually does and in what order (and it's not well documented anywhere). Especially WP Query, hooks and actions should have better explanation somewhere. Filters and something like "walker" are unknown subjects for me, too (to use these you often need to know what actually happens as default action and there is no easy way to just print that in variable). Scripts like in your link are really helpful. – Paul Nov 14 '12 at 22:09

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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