4 Ways You Can Make Your Reps More Productive Today – Download Now

Shortcodes are one of the wonders of WordPress and allows the developer an easy way to provide a functionality to the end user. However, it can be slightly tricky to add a script or a stylesheet to a shortcode which only loads when the shortcode is there (so basically instead of loading the script/stylesheet sitewide WordPress only loads it when the content contains the shortcode).

Basically the trick is to register the style/script and then enqueue it only when you need it.

So in your functions.php (or main plugin file) do something like this:

[php] add_action( ‘init’, ‘my_shortcode_scripts_styles’ );   //Hook your function to when WP initializes
function my_shortcode_scripts_styles() {
wp_register_style( ‘my-shortcode-style’, ‘url-to-the-stylesheet’);
}
//The function above registers the style (or scripts if you need those too) [/php]

Remember to change the parameters to suit your needs. Then in your function that renders the shortcode do this:

[php] wp_enqueue_style( ‘my-shortcode-style’ ); [/php]