Custom JavaScript can add behaviour to a WordPress website, such as responding to a button click. This guide explains how to load a JavaScript file through a child theme.

Before you begin

Use an active child theme, back up its files and test on a staging copy. Parent-theme edits may be overwritten by updates.

Upload the script

  1. Create custom.js containing your JavaScript.
  2. Using your hosting file manager or file-transfer client, create a js folder inside the active child theme’s directory.
  3. Upload the file there, giving a path such as wp-content/themes/your-child-theme/js/custom.js.

WordPress does not normally allow .js uploads through the Media Library. Do not change its permitted file types to follow this procedure.

Register the script

Add this code inside the child theme’s existing functions.php PHP section. Do not add another <?php tag inside that section.

function whuk_enqueue_custom_script() {
    wp_enqueue_script(
        'whuk-custom-js',
        get_stylesheet_directory_uri() . '/js/custom.js',
        array(),
        '1.0',
        true
    );
}
add_action( 'wp_enqueue_scripts', 'whuk_enqueue_custom_script' );

The empty array indicates no registered dependencies. Declare any required scripts there. Change the version when updating the file to help browsers fetch the new copy.

Test the result

Save, clear any site cache and load a page using the script. Check its behaviour and the browser console for errors. Restore the backup if the website stops loading.