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.
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.
Share Improve this question asked Aug 19, 2019 at 14:25 DuncanDuncan 31 bronze badge 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 Commented Aug 19, 2019 at 14:32
1 Answer
Reset to default 1Just 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745232441a4617739.html
评论列表(0条)