Whilst it is easy enough to add standard <script> tags to your themes header, there are times (especially when working with pre-built themes that may receive updates) when you want to register a new script file without modifying the theme templates. This is useful when you have a new UI or JQuery widget that you want to add to your site or when you just want to add some custom logic to an existing page or post.
Thankfully it’s very easy to register a new script file in WordPress without having to go anywhere near the templates by using the new “Child Theme” functionality and adding a few lines of code to the Functions.php file.
Just follow these simple steps:
add_action( 'wp_enqueue_scripts', 'enqueue_and_register_my_scripts' ); function enqueue_and_register_my_scripts(){ wp_register_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js' ); }
Also if you want to add a script which only occurs on a specific page or relies on other scripts then you can do the following:
function enqueue_and_register_my_scripts(){ if ( is_page( 'careers' ) ){ // Enqueue a script that has both jQuery (automatically registered by WordPress) // and my-script (registered earlier) as dependencies. wp_enqueue_script( 'my-careers-script', get_stylesheet_directory_uri() . '/js/my-careers-script.js', array( 'jquery', 'my-script' ) ); } }
And that’s all there is to it, happy scripting!