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!

1
  • Why does it need to be in the header?CommentedAug 31, 2017 at 8:00

2 Answers 2

4

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.

    2

    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

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.