0

I have a function I wish to use in 10 different javascript files (each are used on a different webpage). I was hoping to avoid copying/pasting the function into every .js file.

The pages all have the same parent page.

Is there a way I can define this function once and call it from each page's .js file?

Thank you in advance.

1
  • Yes this should be easy to do. How are you including the current per-page script files though - with wp_enqueue_script, per page or template name? That should be easy to extend to include the parent page's script too.
    – Rup
    Aug 19, 2019 at 14:32

1 Answer 1

1

Just define the function in its own separate JS file, and load that file alongside the page-specific files. The "WordPress way" would be to register the script containing the shared function(s) and then set it as a dependency of the other scripts:

wp_register_script( 'my-functions', get_theme_file_uri( 'js/functions.js' ) );

if ( is_page( 1 ) ) {
    wp_enqueue_script( 'my-page-1', get_theme_file_uri( 'js/page-1.js' ), [ 'my-functions' ] );
}

if ( is_page( 2 ) ) {
    wp_enqueue_script( 'my-page-2', get_theme_file_uri( 'js/page-2.js' ), [ 'my-functions' ] );
}

// etc.
2
  • Great, thank you! 1 quick question - why is not necessary to register the 'my-page-1' script? Or did you leave that out for simplicity? Cheers
    – Duncan
    Aug 19, 2019 at 15:40
  • If you enqueue a script that's not already registered it will be automatically registered. Registering the first script was necessary because we needed to use it as a dependency. You'd also register, rather than enqueue, if the logic for enqueuing existed in multiple places and you didn't want to have to repeat the path each time. Aug 20, 2019 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.