How to add javascript just before the closing body tag in the footer of WordPress

I’m following some of the other people’s advice here about adding my js file before the closing body tag but it doesn’t seem to work for me.

If someone would be so kind as to check this for me please?

Read More
<?php
  /*load the js file into the footer*/
  function myscript() 
  {
   if( wp_script_is( 'jquery', 'done' ) ) {
  ?>
     <script type="text/javascript" src="js/scripts.js"></script>
  <?php
  }
 }
  add_action( 'wp_footer', 'myscript' );
?>

Many thanks

EDIT:————————————————

This is the short solution..
<script language="javascript" src="<?php bloginfo('template_directory'); ?>/js/scripts.js"></script>

not the right answer though is it?

EDIT—————————————————

This is what I am trying based on the WP codex examples and your points Fischi but think I am still doing something wrong..

function my_scripts_method() {
wp_enqueue_script(
    'myscript',
    get_bloginfo('template_directory') . '/js/scripts.js',
    array( 'jquery' ), 
    '', 
    true
);
 }    

 add_action('wp_enqueue_scripts', 'my_scripts_method');

The file still doesn’t load into the footer.

Related posts

Leave a Reply

1 comment

  1. You should always add javascript (and styles) with the WordPress function wp_enqueue_script()

    Works like this:

    wp_enqueue_script( 
     $handle // the name of your enqueued file, in your case 'myscript'
    ,$src    // source of your file, can be external, or for your example: get_bloginfo('template_directory') . '/js/scripts.js'
    ,$deps   // does your javascript depend on another javascriptfile? for example jquery? pass an array of arguments specifying all the dependencies: array( 'jquery' )
    ,$ver   // version number of your javascript
    ,$in_footer // this is what you need: true
    );
    

    after setting the $in_footer to true, it gets enqueued in the wp_footer() action, usually right before the ending of the body tag.

    so, for you:

    wp_enqueue_script( 'myscript', get_bloginfo('template_directory') . '/js/scripts.js', array( 'jquery' ), '', true );
    

    does the trick.

    Note: Not all themes do (though all themes should) call wp_footer(); in their footer / just above the closing </body> tag.