Yes, create a separate JS file and store it in your plugin or theme folder, lets call it example.js. This file should contain all the common function you need to execute in multiple pages, page-specific functions should go to a separate file.
After you’ve written your code in the example.js you need to include it on WordPress, to do this you need to use this function
function my_scripts() {
// Page ID, title, slug, or array of such.
// e.g. is_page('My page title') - page title
// e.g. is_page(2) - page id
// e.g. is_page('my-page-title') - page slug
// e.g. is_page( array( 'page1', 'page1')) - in this example an array of page slugs.
// Check out the references for more on this function.
if ( is_page( array( 'about-us', 'contact', 'management' ) ) {
wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
You can put this function in functions.php. If the file is in your theme directory then use this
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/example.js', array(), '1.0.0', true );
Tip:
If the example.js is in your plugin folder then you need to use
plugin_dir_url( __FILE__ ) instead of get_template_directory_uri() where __FILE__ is a PHP constant for current file path.
To set a variable and use its value across different pages in your JS file, you need this function.
wp_localize_script('script-name', 'array_name', array(
'variable_name' => 'Variable value'
)
);
Note:
wp_localize_script MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script().
References:
- wp_enqueue_script() – Used to actually enqueue the script
- wp_localize_script() – Used to pass any variables/data from WordPress/PHP to JS
- get_template_directory_uri() – Retrieve theme directory URI.
- is_page() – Condition to check if you want to load the JS on specific pages only.
- plugin_dir_url() – Get URL for the plugin directory.
- __FILE__ – PHP constant