admin管理员组文章数量:1415484
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.
本文标签: How to inherit custom javascript from parent to child pages
版权声明:本文标题:How to inherit custom javascript from parent to child pages? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745232441a2648885.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论