douluan5444 2014-02-04 16:36
浏览 173
已采纳

如何在WordPress子主题中正确加载和调用Javascript?

I already searched several hours for a proper tutorial that explains how to correctly incorporate Javascript in a WordPress website, but could not find a decent explanation.

I am running WordPress 3.8.1 with the Genesis Framework and the sample child theme on my localhost, i.e. I do all edits in the functions.php and style.css of my child theme.

On the front page I would like to call some Javasript/jQuery, a fullscreen background slideshow called Vegas.

So I created a js-folder in the child theme's directory, to which I copied jquery.vegas.js and added the following to my functions.php:

//* Adds Vegas slideshow to the front page

add_action( 'wp_enqueue_scripts', 'front_page_slideshow' );

function front_page_slideshow() {

  wp_register_script( 'jquery.vegas', get_stylesheet_directory_uri() . '/js/jquery.vegas.js', array('jquery'), '1.3.4', true );

  if ( is_front_page() ) {
    wp_enqueue_script('jquery.vegas');
    }

}

Furthermore, I added the relevant CSS-classes of jquery.vegas.css to my style.css.

My problem is that I don't know, where to place the code, that triggers the script execution. According to the Vegas-documentation, the script executes by placing e.g. the following javascript just before the closing body-tag:

$.vegas('slideshow', {
  backgrounds:[
    { src:'/img/bg1.jpg', fade:1000 },
    { src:'/img/bg2.jpg', fade:1000 },
    { src:'/img/bg3.jpg', fade:1000 }
  ]
})('overlay', {
  src:'/vegas/overlays/11.png'
});

I unsuccesfully tried to place it in an additional php-file and called it with a hook in functions.php with the following:

add_action( 'genesis_after_footer', 'slideshow' );

function test() {
    if (is_front_page()) 
    require(CHILD_DIR.'/slideshow.php');
}

However, the script does not execute. I would appreciate your help and advice on this.

  • 写回答

2条回答 默认 最新

  • douhuanchi6586 2014-02-04 17:36
    关注

    You have to use the jQuery noConflict wrapper WordPress provides.

    Instead of

    $.vegas();
    

    you have to use

    jQuery.vegas();
    

    That's why you get Cannot call method of undefined, because $ is not defined in WordPress, it's called jQuery.

    If you want to use a lot of code that uses the $ shorthand you can use this trick to spare you rewriting everything:

    jQuery(document).ready(function($) {
        // Inside of this function, $() will work as an alias for jQuery()
        // and other libraries also using $ will not be accessible under this shortcut
        $.vegas(); // this will work in here.
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大