How to Properly Modify JavaScript Files in a Parent Theme

I recently ran into a situation where I needed to modify a JavaScript file present in a parent theme. It was doing almost what I wanted, but not quite.

The correct way to do this is not to modify the file itself, because if your theme ever updates you’ll lose your changes. Rather, you want to follow these steps:

  1. Copy the JavaScript file into your child theme and make the necessary changes.
  2. Dequeue the parent theme file.
  3. Enqueue the child theme file.

This week’s video guide shows you how:

Important Code

The key code from the video guide is as follows:

/* Put this in the functions.php of your child theme */

add_action( 'wp_enqueue_scripts', 'wpshout_dequeue_and_then_enqueue', 100 );

function wpshout_dequeue_and_then_enqueue() {
    // Dequeue (remove) parent theme script
    wp_dequeue_script( 'parent_script_to_modify' );

    // Enqueue replacement child theme script
    wp_enqueue_script(
        'modified_child_script',
        get_stylesheet_directory_uri() . '/js/modified-child-script.js',
        array( 'jquery' )
    );
}

The important thing to understand in the call to wp_dequeue_script() is the slug of the original script that we want to remove—in this case, parent_script_to_modify.

You’ll most easily find this slug in the call to wp_enqueue_script that originally enqueued that script. (So when we set 'modified_child_script' as the first argument of our own wp_enqueue_script, we’re setting that script’s slug equal to modified_child_script, and that’s the slug we’d use to dequeue that script as well.)

This Works on Plugin Scripts, Too

This isn’t just for themes. The basic mechanism of wp_dequeue_script() for unwanted and untouchable JS code, plus wp_enqueue_script() for the code you do want, works for modifying plugin scripts as well. And you follow almost the same process for CSS stylesheets, except with wp_dequeue_style() and wp_enqueue_style() instead of _script().

Happy dequeueing!


6 Responses

Comments

Add a Comment

Your email address will not be published. Required fields are marked *