How to inherit custom javascript from parent to child pages?

I have a function I wish to use in 10 different javascript files (each are used on a different webpage). I was hoping to

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
Add a comment  | 

1 Answer 1

Reset to default 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745232441a4617739.html

相关推荐

  • How to inherit custom javascript from parent to child pages?

    I have a function I wish to use in 10 different javascript files (each are used on a different webpage). I was hoping to

    8小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信