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.
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.
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