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条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题