Adding custom script files to a WordPress theme
  • 25
    Dec

Adding custom script files to a WordPress theme

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:

  1. If you have not done so already you need to create a Child Theme which allows you to override functionality in your current theme without modifying the theme files. This allows you to make changes to the theme without risking the changes being lost when/if the theme is updated. To create a child theme just follow this easy guide from the WordPress Codex (http://codex.wordpress.org/Child_Themes).
  2.  Once you have created your child theme the next step is to open up the Functions.php file in your favourite text/code editor.
  3.  Finally you need to use the wp_enqueue_script() function to register your script with the site so it will be added to the html header. The full function reference is here (http://codex.wordpress.org/Function_Reference/wp_register_script) but if you just want to add a simple script the copy/paste and modify the following code:
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!

Leave a Reply

Contact Us