I want to include a script in a shortcode output, so I am trying this:
function my_shortcode( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
), $atts));
wp_enqueue_script('custom-script');
}
I have registered the script already and enqueue it if the above shortcode is used.
However I want to include the file only once, even if the shortcode is used multiple times. Currently, if the shortcode is used multiple times, it will include the script for each time. Is it possible?
The WordPress enqueue system should prevent the inclusion of the same script multiple times, and does when I test it. For example, the following enqueues a Core script and echo
s a counter. If I put this shortcode into a post 4 times, I get “0123” but the media script only loads one time. The same test works with several other scripts I tried.
function my_shortcode( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
), $atts));
static $counter = 0;
echo $counter++;
wp_enqueue_script('wp-mediaelement');
}
add_shortcode('enq','my_shortcode');
If you are getting the same script loaded over and over, there is a problem with your site, but I am not sure where start guessing at what.