Overwriting WordPress plugin javascript files
CHALLENGE: change the content of the .js file without editing plugin source code
SOLUTION: use the script_loader_tag hook
WordPress is a popular CMS that uses plugins to extend its functionality. Sometimes, we need to customize the way the plugin works. For the PHP part – we can often use filters and actions prepared by the author of the plugin. The customization of plugin behavior by using filters ensures future compatibility with new plugin versions.
Deregistering the file
To customize the .js file, which is included in the plugin, we can follow a typical solution: dequeue and deregister the plugin file and enqueue our new file (with new content). The downside of this solution is that now the order of the .js file can be different. Also, it might not work correctly if the plugin used wp_localize_script for translating javascript strings.
Overwriting javascripts
We’re going to force the plugin to use our .js file instead of the originally enqueued file. Using the script_loader_tag filter, we can check when the file loads and replace the path to the file. The new file will be stored in our child-theme assets directory. We need to know 2 things: script handle (used in the wp_enqueue_script function) and script original path.
/**
* Way of replacing original wordpress plugin .js file
* ( to overwrite file code without editing plugin source code )
*/
add_filter("script_loader_tag", "ct_script_loader_tag3", 90, 2);
function ct_script_loader_tag3($tag, $handle){
if('contact-form-7-js' !== $handle){
return $tag;
}
$new_file = 'themes/child-theme/assets/js/custom-contact-form-7.js';
return str_replace( 'plugins/contact-form-7/includes/js/index.js', $new_file, $tag );
}
Troubleshooting
- I use cache / minify / autoptimize plugin for JS concatenation and the ‘script_loader_tag’ filter doesn’t work
- Try to change filter priority or add a particular javascript file to the ‘ignored list’ / excluded files in cache plugin settings.
Make sure you follow us for other useful tips.