duanhuan5409
duanhuan5409
2015-01-18 04:24

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

已采纳

I am using wordpress and I have some custom js in an external file in the root of my child theme. I want the reference to this js file written to the very end of the html document just before the closing body tag. I first tried hardcode the reference into 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. 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...

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. 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? Do I need to add something to header.php? or footer.php?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doumao6212 doumao6212 6年前

    It is probably the path to your javascript that's causing the problem. get_template_directory_uri() returns the path to your theme rather than the path to your site. 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.

    Instead try 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. '/scripts.js'

    点赞 评论 复制链接分享

相关推荐