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

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.

Leave a Comment