繁体   English   中英

如何将 js 文件添加到页面模板 wordpress

[英]How to add js file to Page Templates wordpress

我使用 Bootstrap 框架为 Hello elementor 模板创建了一个页面模板...但是无论我做什么,我都无法将 .js 文件作为模板引入...谢谢您的帮助

 <?php /** * Template name: test */?> <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/account-page/css/style.css" type="text/css" media="screen" /> <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/account-page/css/woocommerce-style.css" type="text/css" media="screen" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="<?php echo get_bloginfo('template_directory');?>/account-page/js/jquery.min.js" type="text/javascript"></script> <script src="<?php echo get_bloginfo('template_directory');?>/account-page/js/popper.js" type="text/javascript"></script> <script src="<?php echo get_bloginfo('template_directory');?>/account-page/js/bootstrap.min.js" type="text/javascript"></script> <script src="<?php echo get_bloginfo('template_directory');?>/account-page/js/main.js" type="text/javascript"></script>

主题所需的任何其他 JavaScript 文件都应使用 wp_enqueue_script 加载。 这确保了正确的加载和缓存,并允许使用条件标签来定位特定页面。 这些是可选的。

像这样将您的脚本排入队列:

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);

$handle 是脚本的名称。

$src 定义脚本所在的位置。

$deps 是一个数组,可以处理新脚本所依赖的任何脚本,例如 jQuery。

$ver 让你列出一个版本号。

$in_footer 是一个 boolean 参数(真/假),它允许您将脚本放置在 HTML 文档的页脚中,而不是放在 header 中,因此它不会延迟加载 DOM 树。

您的队列 function 应该如下所示:

function my_theme_name_scripts() {
if ( is_page_template( 'test.php' ) ) {
    wp_enqueue_script( 'main', get_template_directory_uri() . '/account-page/js/main.js', array('jquery'), '1.0.0', true );
    wp_enqueue_script( 'popper', get_template_directory_uri() . '/account-page/js/popper.js', array('jquery'), '1.0.0', true );
    wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/account-page/js/bootstrap.min.js', array('jquery'), '1.0.0', true );

}
}
add_action( 'wp_enqueue_scripts', 'my_theme_name_scripts' );

function 应放在您的子主题中的 functions.php 中。

请注意条件逻辑以确保 function 正在您的 test.php 页面模板中执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM