A better way to override plugin's JS files?

All we need is an easy explanation of the problem, so here it is.

I’m modifying some functionality of a theme i’m using, which already set up a .js file inside a plugin to handle the paypal checkout process. I had to modify the code so I renamed a few elements and basically copied the old js file to a new file and made the changes.

It works and everything is fine, but I wonder if there’s a better way to do it in WordPress? It doesn’t feel right to modify so much just so I could change a few lines of code inside.


How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Extending the above comment:

Directly changing the files of the plugin or theme is not a good practice as once the plugin/theme is updated, you will loose the changes. Instead use child theme in case of themes and hook to required actions in case of plugins.

In your case since you are only changing the script in plugin and they might have enqueued(they should be) with wp_enqueue_script hooked to wp_enqueue_scripts. You can dequeue that script using wp_dequeue_script all you have to do is findout the script handle from the original plugin. Then you need to enqueue the changed script.

Method 2

Same problem here, but “wp_dequeue_script” was not enough. I wanted to override the “waypoints” loaded by WPBakery plugin. Adding “wp_deregister_script” the code is working.

define( 'MY_CHILD_URI', get_stylesheet_directory_uri().'/' );

add_action('wp_enqueue_scripts', 'mytheme_scripts');

function mytheme_scripts() {
  wp_dequeue_script( 'waypoints' );
  wp_deregister_script( 'waypoints' );
  wp_enqueue_script( 'waypoints',  MY_CHILD_URI . 'assets/js/jquery.waypoints.min.js', array('jquery'), '', true );

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply