I’ve created some shortcodes and for some of these, I need to load particular scripts on demand.

I’ve included by default in my function.php file

vendor.js
myscript.js

When i load the shortcode, i need to include a separate script between the two above (meaning that myscript.js requires the new script to be included before it to work).

I’ve created the shortcode like this:

function callbackService()
{
    ob_start();    
    get_template_part('hg_custom_shortcodes/callback');
    return ob_get_clean();   
}
add_shortcode('callbackService', 'callbackService');

the template is loading an angular app.

I then tried to load my script (the one that needs to be included only when the shortcode is loaded) by changing the snippet above to this:

function callbackService()
{
    ob_start();    
    wp_enqueue_script('angular-bundle', get_template_directory_uri() . '/scripts/angular-bundle.js', array(), false, true);
    get_template_part('hg_custom_shortcodes/callback');
    return ob_get_clean();   
}
add_shortcode('callbackService', 'callbackServhowever

The script is included, hovewer i think it’s included after myscript.js and the whole shortcode (angular app) is not working as “Angular is not defined”.

How can i tell the enqueue to load the script after?
I know that usually i would change the add_action() priority, but in this particular case there’s no add_action involved and i don’t know what else to try.

Any suggestions? thanks

3 Answers
3

wp_enqueue_script is not going to work in a shortcode, this is because of the loading order.

You could use wp_register_script and then you could wp_enqueue_script in you shortcode function like this example:

// Front-end
function front_end_scripts() {
    wp_register_script( 'example-js', '//example.com/shared-web/js/example.js', array(), null, true );
}
add_action( 'wp_enqueue_scripts', 'front_end_scripts' );

Then you use this in your shortcode:

function example_shortcode() {

   wp_enqueue_script( 'example-js' );
   return; // dont forget to return something

}
add_shortcode( 'example-shortcode', 'example_shortcode' );

Furthermore, you could use has_shortcode to check if a shortcode is loaded:

function custom_shortcode_scripts() {
global $post;
if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-shortcode') ) {
    wp_enqueue_script( 'custom-script');
}
}
add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');

Leave a Reply

Your email address will not be published. Required fields are marked *