I want load some scripts and style only for a specific shortcode. I used

if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my_shortcode') ) {}

It works when I put my shortcode on page but it does not work when I put my shortcode in page template. Like the following one in index.php file:

echo do_shortcode( ' [ my_shortcode ] ' );

Is there any way to load scripts for [ my_shortcode ] in do_shortcode(' [ my_shortcode ] ') without checking page template.

  • Have you tried reading the page template then? there's get_page_template to get the template path for current page, e.g print_r( has_shortcode(file_get_contents(get_page_template()), "my_shortcode") );
    – Ismail
    Jan 29, 2017 at 16:50

2 Answers 2


Add a filter to pre_do_shortcode_tag and check if $tag is the same as your shortcode tag. If it is, enqueue a script in the footer.

add_filter( 'pre_do_shortcode_tag', function( $a, $tag, $attr, $m ) {
  if( 'my_shortcode_tag' === $tag ) {
    wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer = true );
  return $a;
}, 10, 4 );

I think there is a better way to enqueue or load your scripts first register the script or styles with wp_register_style and wp_register_script.

After registering you can load the script/style when required. For example when you render a shortcode with wp_enqueue_style("your_style") and wp_enqueue_script("your_script").


[my_shortcode other parameters]

Add action for the script by registering and enqueuing when required.

function prefix_my_shortcode_wp_enqueue_scripts() {
    wp_register_script( 'my-shortcode-script', plugins_url( 'path/myscript.css' ) );

add_action( 'wp_enqueue_scripts', 'prefix_my_shortcode_wp_enqueue_scripts' );

Your shortcode function

function prefix_function_my_shortcode( $attributes ) {
    extract( shortcode_atts(
    // your shortcode array args

    wp_enqueue_script( 'my-shortcode-script' );

    return 'your shortcode output;

add_shortcode( 'my_shortcode', 'prefix_function_my_shortcode' );

Hope that answers your question. Let me know if that helps out.

  • Loading script in shortcode will work but style will not work. Because style load before running shortcode.
    – sayful
    Jan 30, 2017 at 5:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.