I’m loading some JavaScript files in the parent theme. The path in the parent theme is:
scripts > custom.js
In the child theme, I’m creating the same path (scripts > custom.js
) and changing some of the jQuery inside the custom.js
file.
The problem is that the changes are not being applied. Is this the wrong way to make changes to these files in the child theme?
Child themes only override php files (like header.php) that are included with functions like get_template_part or get_header, etc.
The correct way to add scripts to WordPress is with wp_enqueue_script. If your parent theme uses this, you can override the JS files by using wp_dequeue_script and enqueuing your own.
Like so…
If the parent theme isn’t using wp_enqueue_script, it’s probably hooking into wp_head (or wp_footer) to echo out the scripts there. So you’d use remove_action to get rid of those functions echoing the scripts out, and then enqueue your own script.
If the script is hard coded into the template file, you’ll just need to replace that template file in your child theme without the script tag.
If they used wp_enqueue_script calls that utilize get_stylesheet_directory_uri, then you shouldn’t have to do anything. Since this isn’t happening, you’ll just have to poke around and see what the theme author did.
In some cases it is important to prioritize both the add_action and the wp_enqueue_script function calls like so:
In this case, wp_enqueue_scripts was called by the parent with a priority of 20120206 (the date) and so this action is added with a priority just barely greater so that it will immediately be dequeued. Then, the enqueue statement that follows that follows is actually prioritized after that to ensure that it loads after the old one was dequeued. The true, in this case is also important because that specifies that it is to be enqueued in the footer, which is where the parent script was first enqueued.
Also, I can’t quite explain it entirely, but I notice that if you are careful with dequeuing the initial script immediately after it being enqueued, it seems you can effectively prevent it from loading in the first place.
call wp_deregister_script before register your own version
Since WordPress Version 4.7 you can use ‘get_theme_file_uri()’ which will first look in your child theme folder and afterwards in the parent theme folder. This way, the file in the child theme will be prioritized.