Why does wp_enqueue_script ignore my ‘wp_head’ hook?

You problem lies with how you are using wp_enqueue_script(). It does not print out the <script src=""></script>, instead it adds it to a list of Javascript files to printed out at the appropriate time.

There is a different hook that is called for when you should add your Javascript and CSS: wp_enqueue_scripts (you use it for CSS too). Your css_head_script() is called too late as the function to print the scripts is called earlier in the wp_head hook.

As for the js_head_scripts(), this will just not as you expect regardless because wp_enqueue_script() does not print the script element. It just adds it the list of scripts to print out. The best you’ll get is conditional tags with nothing inside them.

Regarding your js_footer_scripts(), you don’t need an extra function for that because wp_enqueue_script() has a parameter for adding the script to the footer instead of the head.

function add_js_and_css() {
  global $wp_scripts;

  // CSS
  // The label should be safe for an ID, and you need the trailing slash
  wp_enqueue_style( 'master-stylesheet', get_template_directory_uri()."/style.css" );

  // Javascript
  // By setting the fifth parameter to true, WP will print it in the footer
  wp_enqueue_script( "my-jquery", "http://code.jquery.com/jquery-1.10.2.min.js", array(), '1.10.2', true );
  wp_enqueue_script( "bootstrap", get_template_directory_uri()."/js/bootstrap.min.js", array('my-jquery'), '3', true );

}
add_action( 'wp_enqueue_scripts', 'add_js_and_css' );

function add_conditional_js() {
  ?>
  <!--[if lt IE 9]
    <script src="https://wordpress.stackexchange.com/questions/134784/<?php echo esc_attr("https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js'); ?>"></script>
    <script src="https://wordpress.stackexchange.com/questions/134784/<?php echo esc_attr("https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js'); ?>"></script>
  <![endif]-->
  <?php 

}
add_action( 'wp_head', 'add_conditional_js' );

Leave a Comment