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

时间:2015-01-18 04:24:52

标签: javascript php wordpress wordpress-theming

我正在使用wordpress,并且在我的子主题的根目录中的外部文件中有一些自定义j。我希望在关闭body标签之前将这个js文件的引用写入html文档的最末尾。我首先尝试将引用硬编码到footer.php中。我验证了外部js文件的引用在html源代码中是正确的,但javascript什么也没做,也没有在firebug中抛出任何错误。外部文件仅包含:

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

所以经过谷歌搜索这个问题一段时间后我发现我需要使用

wp_register_script

wp_enqueue_script

我找到了文档herehere,但我对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?

1 个答案:

答案 0 :(得分:1)

这可能是导致问题的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'