Conditional Script Loading Revisited

In 2010 I wrote a tutorial for loading JavaScript using the WordPress API. The main problem was how to enqueue a script only when needed; for example, when a certain shortcode was present on the page.

Since WordPress 3.3, you can skip all the Yoda acrobatics; just call wp_enqueue_script() inside the shortcode handler:

add_shortcode('myshortcode', 'my_shortcode_handler');
 
function my_shortcode_handler($atts) {
	wp_enqueue_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);

	// actual shortcode handling here
}

If you’re interested in the gory details, here’s the trac ticket.

comments powered by Disqus