繁体   English   中英

如何在Wordpress中从子主题运行外部js文件

[英]How can I run external js file from child theme in wordpress

我正在使用wordpress,并且在子主题根目录的外部文件中有一些自定义js。 我希望将此js文件的引用写在html文档的最后,就在结束body标签之前。 我首先尝试将引用硬编码到footer.php中。 我验证了在html源中对外部js文件的引用是正确的,但是javascript却什么也没做,并且在firebug中也没有引发任何错误。 外部文件仅包含:

jQuery(document).ready(function(){
    alert('hello')
});

所以在搜索了一段时间之后,我发现我需要使用

wp_register_script

wp_enqueue_script

我在这里这里都找到了文档,但是我对php不是很熟悉。

目前,我添加了:

add_action('wp_enqueue_scripts', 'load_javascript_files');
function load_javascript_files() {
    wp_register_script('scripts', get_template_directory_uri() . 'wp-content/themes/maya_child/scripts.js', array('jquery'), true );
    wp_enqueue_script('scripts');
}

到我的孩子主题的functions.php文件。 结果是对我的自定义脚本文件的引用根本不会在源代码中打印出来

我可能错过了一步,还是我搞砸了php? 我需要在header.php中添加一些内容吗? 或footer.php?

可能是您的JavaScript路径引起了问题。 get_template_directory_uri()返回主题的路径,而不是站点的路径。 另外,当您使用子主题时,此函数仍会返回父主题的uri-因此,这不是最佳选择。

而是尝试get_stylesheet_directory_uri()

add_action('wp_enqueue_scripts', 'load_javascript_files');
function load_javascript_files() {
    wp_register_script('scripts', get_stylesheet_directory_uri() . '/scripts.js', array('jquery'), null, true );
    wp_enqueue_script('scripts');
}

请注意,这些函数均未在uri上返回斜杠,因此您需要在路径的其余部分之前添加该斜杠。 '/scripts.js'

暂无
暂无

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

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