duanhuan5409 2015-01-18 04:24
浏览 224
已采纳

如何在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 2015-01-18 04:49
    关注

    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'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题