0

I'm trying to enqueue a JavaScript file in the header of my website.

If I add the following in my main plugin file the JS is included in the header:

function wpdocs_theme_name_scripts() {

    wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');
    wp_enqueue_script('googlesearch');

}

add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

But I want to include the JS for a specific shortcode only, I add the following in the main plugin file:

function wpdocs_theme_name_scripts() {

    wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');

}

add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

And the following in the shortcode:

wp_enqueue_script('googlesearch');

Now the JS file is included in the footer of the website.

I've tried manually specifying that the JS should be loaded in the header like so but it still loads it in the footer:

wp_enqueue_script( 'googlesearch', 'https://maps.googleapis.com/maps/api/js', array(), '1.0.0', false );

Does anyone have any idea why this is happening? Appreciated any help!

  • Why does it need to be in the header? – Jacob Peattie Aug 31 '17 at 8:00
1

Page is created and output in the following order: header, content, footer. Shorcode is executed during the construction of the page content, when header is already output on the page. So, it is impossible to add any script to header on this stage: it is too late.

|improve this answer|||||
1

While it is a pretty "dirty" fix, you can achieve the wanted effect like this:

function wpdocs_theme_name_scripts() {

    wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');

    if(is_singular()){
          global $wp_query;
          $postid = $wp_query->get_queried_object_id();
          $mypost = get_post($postid);
          $unfiltered_content = $mypost->post_content;
          if(has_shortcode($unfiltered_content,'<SHORTCODE WITHOUT BRACKETS>')){
               wp_enqueue_script('googlesearch');
          }
    }    
}

add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

Happy Coding, Kuchenundkakao

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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