2

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.

    2 Answers 2

    4

    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.

    5
    • So, add_shortcode is aware of this and it's not too early or too late to register and enqueue this?
      – Atadj
      CommentedNov 14, 2012 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.
      – fuxia
      CommentedNov 14, 2012 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!
      – Atadj
      CommentedNov 14, 2012 at 19:34
    • @Paul See my update for a plugin to inspect the load order.
      – fuxia
      CommentedNov 14, 2012 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.
      – Atadj
      CommentedNov 14, 2012 at 22:09
    0

    We can indeed conditionally load CSS and JS files via shortcode conditionally, when the shortcode is present and without using any overly elaborate functions:

    Refer to comment #348349 here: Enqueue Scripts / Styles when shortcode is present

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.