如何在WordPress的Hello Elementor自定义页面模板中引入JS文件
问题修复方案
资源引入方式不符合WordPress规范是核心问题,直接硬编码脚本标签在模板顶部容易和WordPress核心、Elementor自带的脚本产生冲突,且会出现重复加载、加载顺序错误的问题,推荐使用官方的
wp_enqueue_scripts钩子统一入队资源。
把以下代码添加到Hello Elementor主题的functions.php文件中即可:add_action( 'wp_enqueue_scripts', 'enqueue_custom_test_template_assets' ); function enqueue_custom_test_template_assets() { // 仅在test自定义模板下加载资源 if ( is_page_template( 'test.php' ) ) { // 入队样式 wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/account-page/css/style.css', array(), '1.0', 'all' ); wp_enqueue_style( 'custom-woocommerce-style', get_stylesheet_directory_uri() . '/account-page/css/woocommerce-style.css', array(), '1.0', 'all' ); wp_enqueue_style( 'font-awesome', 'https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', array(), '4.7.0', 'all' ); // 入队脚本,依赖WordPress自带jQuery,避免重复引入 wp_enqueue_script( 'popper-js', get_stylesheet_directory_uri() . '/account-page/js/popper.js', array('jquery'), '1.0', true ); wp_enqueue_script( 'bootstrap-js', get_stylesheet_directory_uri() . '/account-page/js/bootstrap.min.js', array('jquery', 'popper-js'), '1.0', true ); wp_enqueue_script( 'custom-main-js', get_stylesheet_directory_uri() . '/account-page/js/main.js', array('jquery', 'bootstrap-js'), '1.0', true ); } }代码中最后一个参数设为
true表示脚本加载在页脚,符合前端性能规范,也能避免DOM未加载完成就执行脚本的问题。路径错误排查:你原代码混用了
stylesheet_directory和template_directory,如果你使用的是Hello Elementor的子主题,template_directory指向父主题路径,stylesheet_directory指向子主题路径,需确认你的account-page资源文件夹放在父主题还是子主题目录下,对应使用get_template_directory_uri()(父主题)或get_stylesheet_directory_uri()(子主题)获取路径。模板完整性检查:如果坚持要直接在模板文件中写脚本标签,需确保你的自定义模板中包含
wp_head()(加在</head>标签前)和wp_footer()(加在</body>标签前)两个函数调用,Elementor、WordPress核心功能都依赖这两个钩子加载资源,缺少会导致所有脚本加载异常。
内容的提问来源于stack exchange,提问作者محمد
相关产品推荐
相关产品推荐

