Wordpress - enqueue script for specific shortcode
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');
Would has_shortcode
help you solve your problem?
On the codex there's an example,
Enqueue some script when some post uses some shortcode
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');