The best practice is the following:
Put your Javascript code in a file, yourcustomjs.js
, and store it in your theme folder. I would recommend yourtheme/js/yourcustomjs.js
.
Be sure that you wrap your script, where needed, in a Document.ready function like the following:
jQuery(document).ready(function($) {
// your code
});
This enables you to ensure the $
shortcut is working.
Afterwards you need to register and enqueue your script. Usually, you do this in your functions.php
, but I always recommend to create a file yourtheme/library/scripts.php
, which is included in functions.php
. This allows you to handle all the Javascript files in one place, with no additional stuff around it.
In your scripts.php
you have to register your Javascript within WordPress.
wp_register_script (
'yourscripthandle', //string $handle: a string to identify this script
get_bloginfo( 'template_url' ) . '/js/yourcustomjs.js', //string $src: Path of your script file
array ('jquery' ), // array $deps = array(): defining which scripts your script is dependend on. In your case, it's jQuery.
'', // string|bool $ver = false: The version of your Script
true //bool $in_footer = false: whether your script should be enqueued in `wp_head()` or `wp_footer()`
);
Now WordPress knows about your script, and you need to tell WordPress to output it, and this is done with wp_enqueue_script()
:
wp_enqueue_script( 'yourscripthandle' );
There you go! If you followed the steps correctly, your script should be loaded in the footer.
BTW: analogous to registering and enqueueing scripts, you should do the same with wp_register_style()
and wp_enqueue_style()