Overwriting JavaScript Files

If you are using child theme, and you find yourself in need to overwrite some JavaScript files from parent theme, then you will soon find out that it is not as easy, as with other .php templates, as child themes automatic use of files added to its directory only concerns .php templates.

However I will now show you the way how you can do it pretty easily without breaking, dependencies or localization of these files.

So lets say you want to change file script.js and make sure your changed version will be loaded independent what changes will occur in theme updates.

Lets start with coping this file (script.js) from main theme to child theme Best would be to put in same location as in main theme so lets put in under js/script.js. So after this operation you should have rife-child-theme\js\script.js
Now it is time you make your changes in these new file, or do it later, just be sure to now operate on this file.

Now we have to rewrite path to original file in parent theme. To do it copy below code to functions.php in child theme

function child_theme_enqueue_scripts() {
    global $wp_scripts;
    $wp_scripts->registered[ 'apollo13framework-script' ]->src = get_stylesheet_directory_uri() . '/js/script.js';
}
//register this after parent theme files, that is why we have priority set to 27
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_scripts', 27 );

In above code you want to change two things(if you wish to overwrite different files). These are:

  • apollo13framework-script – it is handle for original file in parent theme
  • /js/script.js – it is path to your new file in child theme

Handles for JavaScript files can be found in main theme in advance\head_scripts_styles.php in function a13_theme_scripts(). They are listed as first argument for calls of wp_enqueue_script() and wp_register_script() like in below example.

wp_enqueue_script('apollo13framework-scripts', A13_TPL_JS . '/script.js', $script_depends, A13_THEME_VER, true );

Anyway, now your changed JavaScript file should be loaded instead of original one. Nice one 🙂

Was this article helpful to you? Yes 1 No