How to include code only on specific pages?

I’m learning about plugins and shortcodes. I noticed that when I activate my plugin its code gets loaded on all of my pages– even pages that don’t have my shortcode. (I don’t mean content vs. admin pages). On some content pages, I use a particular shortcode and on other content pages, I don’t– but in any case, the plugin’s code is loaded. How do I make it so that the the plugin is included only on pages where the shortcode is used?

More Detail:

Let’s say I’ve got a plugin that makes a lightbox. I activate the plugin. On my “Cool Images” page, I use shortcode to make a lightbox. When I check View Source on my “About” page, which doesn’t use the lightbox shortcode, I see that the lightbox plugin’s code has been loaded. My pages will load faster if I write my plugin so that its code is only loaded on the pages where it’s needed. Is this possible? Otherwise, I’ll have code for lots of plugins loaded on pages unnecessarily. Any ideas?


WP v3.3 gave us the ability to run wp_enqueue_script in the middle of a page. Ticket 9346

This has made it much easier to include your JS with better granularity (when using shortcodes, at least). Here, jquery will be only included when our shortcode is fired.

function get_slideshow() {
  // Do some stuff...

  // Load up scripts right from within our shortcode function (requires WP 3.3+)
  wp_enqueue_script( 'jquery', array(), null, true  ); 

add_shortcode( 'cool_slideshow', 'get_slideshow' );

Leave a Comment