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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 echos 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.
Method 2
You can use wp_script_is() to determine if a script is enqueued – and use it in a conditional, like this:
if( ! wp_script_is( 'custom-script', 'enqueued' ) ) {
// your code here
}
wp_script_is() takes two parameters – $handle and $list – the latter can be: registered, enqueued/queue, done or to_do; and it returns true or false.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0