[英]How can I run external js file from child theme in wordpress
I am using wordpress and I have some custom js in an external file in the root of my child theme. 我正在使用wordpress,并且在子主题根目录的外部文件中有一些自定义js。 I want the reference to this js file written to the very end of the html document just before the closing body tag.
我希望将此js文件的引用写在html文档的最后,就在结束body标签之前。 I first tried hardcode the reference into footer.php.
我首先尝试将引用硬编码到footer.php中。 I verified that the reference to the external js file was correct in the html source but the javascript did nothing, and also did not throw any errors in firebug.
我验证了在html源中对外部js文件的引用是正确的,但是javascript却什么也没做,并且在firebug中也没有引发任何错误。 The external file contained only:
外部文件仅包含:
jQuery(document).ready(function(){
alert('hello')
});
So after googling this problem for a while I found that I will need to use 所以在搜索了一段时间之后,我发现我需要使用
wp_register_script
and 和
wp_enqueue_script
I found documentation here and here but I am not very familiar with php... 我在这里和这里都找到了文档,但是我对php不是很熟悉。
Currently, I have added: 目前,我添加了:
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');
}
to my child theme's functions.php file. 到我的孩子主题的functions.php文件。 The result is that the reference to my custom scripts file does not print out in the source at all
结果是对我的自定义脚本文件的引用根本不会在源代码中打印出来
Am I maybe missing a step, or have I screwed up the php? 我可能错过了一步,还是我搞砸了php? Do I need to add something to header.php?
我需要在header.php中添加一些内容吗? or footer.php?
或footer.php?
It is probably the path to your javascript that's causing the problem. 可能是您的JavaScript路径引起了问题。 get_template_directory_uri() returns the path to your theme rather than the path to your site.
get_template_directory_uri()返回主题的路径,而不是站点的路径。 Also, when you're using a child theme, this function still returns the uri of the parent theme - so it's not the best choice here.
另外,当您使用子主题时,此函数仍会返回父主题的uri-因此,这不是最佳选择。
Instead try get_stylesheet_directory_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');
}
Note that neither of those functions returns a trailing slash on the uri, so you need to add that before the rest of your path eg. 请注意,这些函数均未在uri上返回斜杠,因此您需要在路径的其余部分之前添加该斜杠。 '/scripts.js'
'/scripts.js'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.