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.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.
You can use
wp_script_is()
to determine if a script is enqueued – and use it in a conditional, like this:wp_script_is()
takes two parameters –$handle
and$list
– the latter can be:registered
,enqueued
/queue
,done
orto_do
; and it returnstrue
orfalse
.