I have two plugins that work together (one is an add-on of sorts). In the “main” plugin, I have a js function in a file located like so:
wp-plugins/main-plugin-name/js/main-js.js
If my secondary plugin, I have another .js file located like so:
wp-plugins/secondary-plugin-name/js/sec-js.js
In this second plugin’s .js file, I want to use a function located in the first .js file. Basically I want the function to be globally available to both plugins.
I have already registered and enqueued the first .js script using the main plugin, but I can’t seem to get the secondary plugin to find the function from the first, and use it.
Here’s my current code:
In first plugin:
add_action( 'wp_enqueue_scripts', 'tps_enqueue_frontend_scripts');
function tps_enqueue_frontend_scripts() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_register_script( 'tps-space-rentals', $plugin_url.'/js/tps-space-rentals.js', array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'jquery-validate', 'jquery-payment', 'jquery-ui-dialog', 'jquery-ui-tooltip') );
wp_enqueue_script( 'tps-space-rentals' );
}
In my other plugin, I have this:
add_action( 'wp_enqueue_scripts', 'tps_stripe_pay_scripts_enq', 20);
function tps_stripe_pay_scripts_enq() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_register_script( 'tps-stripe-payments', $plugin_url.'js/tps-stripe-payments.js', array('jquery', 'tps-space-rentals'), '', true );
wp_enqueue_script( 'tps-stripe-payments' );
}
1 Answer
The only thing that determines whether a function is available in another script is if it has been loaded before the other script attempts to use it. This is simply a matter of putting the <script></script>
tag for the script with the function you need to use before the tag of the script that needs to use it*.
The most reliable way to guarantee that the script you depend on has loaded before the script that needs it is to use the dependencies argument of wp_enqueue_script()
:
wp_enqueue_script( 'dependency', '/path/to/dependency.js' );
wp_enqueue_script( 'script', '/path/to/script.js', array( 'dependency' ) );
The 3rd argument is an array of handles (the first argument) for scripts that the script depends on. This ensures that 'dependency'
will be loaded whenever 'script'
is enqueued, and before it.
*Unless you’re doing something unusual like loading scripts asynchronously, which WordPress doesn’t support with wp_enqueue_script()
out of the box.